Dec 18, 2014

Thread Local Storage in Java

This post is part of the Java Advent Calendar and is licensed under the Creative Commons 3.0 Attribution license. If you like it, please spread the word by sharing, Tweeting, FB, G+, etc!      
It was also republished under

One of the rarely known features in Java among developers is Thread-local storage. The idea is simple, and the need for it comes in  scenarios where we need data that is, well, local for the thread. For example, if we have two threads that refer to the same global variable but we want them to have separate values independently initialized of each other.
Most major programming languages have implementations of the concept. For example, C++11 has the thread local keyword, and Ruby has chosen an API approach.
Java has also an implementation of the concept with  java.lang.ThreadLocal<T> and with subclass java.lang.InheritableThreadLocal<T> since version 1.2, so nothing new and shiny here.
Let's say that for some reason we need to have a Long specific for our thread. Using Thread local that would simply be:

public class ThreadLocalExample {

  public static class SomethingToRun implements Runnable {

    private ThreadLocal threadLocal = new ThreadLocal();

    public void run() {
      System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());

      try {
      } catch (InterruptedException e) {

      System.out.println(Thread.currentThread().getName() + " " + threadLocal.get());

  public static void main(String[] args) {
    SomethingToRun sharedRunnableInstance = new SomethingToRun();

    Thread thread1 = new Thread(sharedRunnableInstance);
    Thread thread2 = new Thread(sharedRunnableInstance);



One possible sample run of the following code will result in:

Thread-0 null

Thread-0 132466384576241

Thread-1 null

Thread-1 132466394296347

In the beginning the value is set to null to both threads, obviously each of them works with separate values since after setting the value to System.nanoTime() on Thread-0 it will not have any effect on the value of Thread-1 exactly as we wanted, a thread scoped long variable. One nice side effect is a case where the thread calls multiple methods from various classes. They will all be able to use the same thread scoped variable without major API changes. Since the value is not explicitly passed through one might argue it difficult to test and bad for design, but that is a separate topic altogether.

In what areas are popular frameworks using Thread Locals?

Spring, being one of the most popular frameworks in Java, uses ThreadLocals internally for many parts - easily demonstrated by a simple GitHub search. Most of the usages are related to the current user's actions or information. This is actually one of the main uses for ThreadLocals in JavaEE world, storing information for the current request like in RequestContextHolder:
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = 
    new NamedThreadLocal<RequestAttributes>("Request attributes");
Or the current JDBC connection user credentials in UserCredentialsDataSourceAdapter. If we get back on RequestContextHolder, we can use this class to access all of the current request information from anywhere in our code. A common use case for this is  LocaleContextHolder, which helps us store the current user's locale. Mockito uses it to store the current "global" configuration and if we take a look at any framework out there is a high chance we'll find it as well.

Thread Locals and Memory Leaks

Now that we've learned about this awesome little feature, let's use it all over the place! Well, we can do that, but if you try a few Google searches, you'll find that most posts out there claim that ThreadLocal is evil. That's not exactly true. It's a nice utility, but in some contexts,  you could easily accidentally create a memory leak.
“Can you cause unintended object retention with thread locals? Sure you can. But you can do this with arrays too. That doesn’t mean that thread locals (or arrays) are bad things. Merely that you have to use them with some care. The use of thread pools demands extreme care. Sloppy use of thread pools in combination with sloppy use of thread locals can cause unintended object retention, as has been noted in many places. But placing the blame on thread locals is unwarranted.” - Joshua Bloch
It is very easy to create a memory leak in your server code using ThreadLocal if it runs on an application server. ThreadLocal context is associated to the thread where it runs and will be garbaged once the thread is dead. Modern app servers use pool of threads instead of creating new ones on each request, meaning you can end up holding large objects indefinitely in your application.  Since the thread pool is from the app server, our memory leak could remain even after we unload our application. The fix for this is simple - free up resources you do not need. One other ThreadLocal misuse is API design. Often I have seen use of RequestContextHolder(that holds ThreadLocal) all over the place, like the DAO layer, for example. Later on, if one were to call the same DAO methods outside a request, for instance, and scheduler, he would get a very bad surprise. Even though, the variables in ThreadLocal are local to the thread they are very much global in your code. So, if you want to avoid maintenance developers hunting you down and taking their revenge, make sure you really need this thread scope before you use it.

More info on the topic

How to Not Hate JavaScript: Tips from the Frontline

This article was originally published on voxxed under,

In my work assisting teams with JavaScript related problems, I’ve noticed some common issues. If you're experiencing frustrations with the language too, this article might be of some assistance. Disclaimer: a few of my tips might be obvious to some of you, but hopefully you’ll find at least some useful nuggets of information here! These pointers are especially useful when dealing with enterprise applications and CMS solutions. This is where we have our code, the CMS code, the code from that team nobody wants to mention...and, of course, all of them are loaded asynchronously.

The Debugger Statement

This is one of the most underused features when dealing with JavaScript, especially since it’s supported by the majority of browsers. The debugger statement was part of the first edition of ECMA Script so it's been here for quite some time.

Fundamentally it’s a simple way of adding a breakpoint. If we have code where we loop over an element list and then process the elements...

...we can add the debugger statement inside the loop so that we have a breakpoint on each iteration:

The triggering of the breakpoint happens when the execution of the code is done in the place where we have added it. In cases where there is no debugger handler - for example in most browsers without dev tools - this statement has no effect.

On the dev tools side, it will appear as if we have manually placed the breakpoint.

Of course, this is not for code you want to leave in production, but it is an extremely useful feature during the development period. It has been a life changing feature for me, especially when dealing with the vendor based JavaScript and a whole lot of callbacks.

Use the Console Luke!

Most of the developers use the console.log in for debugging purposes, but did you know about console.warn, console.error, and :

All of these support C style formatted output like:

console.log("Hello %s", "Brian");

There are also plenty of JS logging frameworks. Proper logging is essential in most programming languages, and JavaScript is no exception to this. Note that not all logging functions are standardized, and you might need to provide fallback for certain browsers. For reference, there is a more extensive article regarding logging in the real world here.

Overview of JS objects using Console.table()

Often we load data from various services and want have a nice view of it on our console - especially when the data is represented as a list of objects. For example, if we were to load a list of beers from (yes this database exists, and it is awesome). Using the HTTP GET beers, call we receive a list of objects. After receiving the list, we just print it out using console.log:

The resulting list is difficult to navigate in the console. It’s tricky to get a clear picture of what the data represents. Even if we were to loop through the data, it would still be tedious. Same goes for any large JavaScript object or a list.

If we were to replace the console.log with console.table and make the call again we'd get this:

Obviously, the data is shown in a table and it is now sortable using the attributes of the objects. This makes the navigation easier. For example, this is a simple way to visually compare two arrays:

console.table([[1,2,3], [2,3,4]]);

would result in more clear version, especially if we had more sub-arrays:

Getting the Call Trace

Sometimes we want to know the call trace, aka "Who called my function". This is often visible when we get a failure - but even on success, we could get the call trace using console.trace :

Note that console.trace is a non-standard functionality and is not something you should have in production. It is, however, supported by major desktop browsers.
Async Call TraceConsole.trace works just fine for normal function calls. In most developer tools, we get the same call trace when we stop on the breakpoint. When the call is async(callback) this information is not available because the scope of the closure(callback function) is limited to the data that it holds. Fortunately, in the newer version of Chrome dev tools we have the flag async. So what previously would have been a portion of the call information... becomes a full call trace containing the scope of the caller and the callback:

Most definitely an essential feature in today's asynchronous world, in my opinion. For an extensive explanation of how the async call trace works, I recommend this HTML5rocks article.

Who’s Changing My Object?: Objects.observe + console.trace

Sometimes objects get some of their properties changed, but we cannot figure out the cause. In this case, objects.observe comes to the rescue. Let's say we want to check for all changes to our person object:

Since we have combined this with the console.trace, we can also see the call trace. Awesome right?

Well, not so much, since at the time of writing only Chrome supports this and it is a non-standard functionality. Fortunately, it is proposed as part of ECMAscript 7. There is also a similar internal variant for this in Gecko based browser Then again, when it comes to debugging, anything we can get is useful. Note that Objects.observe primary function is not debugging, but it is a great side effect.

Who’s Changing My DOM/HTML Element - Aka, Who’s F***ing Up My Code?

In complex applications, we may end up in a situation where we do not know how a certain HTML element got changed, moved, added, or had some of it's attributes modified. One way to figure out is to attach the now deprecated mutation event listeners. The API for this is far from ideal, and there are other shortcomings. The newer browser version comes with an object called MutationObserver, which enables us to watch a certain DOM element.

Suppose we wanted to list all mutations on the entire document, where the document can also be any DOM element selected:

There is also the non-programmable solution we can use in Chrome called DOM breakpoints which still uses mutation events in the background.

Server Side Logging of Client Side Errors

As simple as that, just add the error handler to the window object and you're done with the client side. The handler can then make an AJAX request to a REST endpoint which will store the error information on your server. You might find out that a client using IE 8 has a lot of issues this way because IE versions predating 9 have no string.trim(). I guess string trim is just not that essential.

Anyway, this what the most basic server side logging of client side errors might look like:

Of course, this is the most basic of solution you can have. There are tons of better solutions out there like or and a more extensive article on Mozilla hacks. There is also a great Hacker News discussion on this topic, but hey, this is certainly a good start!
Use Google Or Other Analytics Tools to Store Data

I know you are way too busy to be writing any backend code. so why not just store the data in Google Analytics?

You can certainly do this, but note that this is a hack, and there are a lot of better commercial options out there like if you want to be really thorough - but even a hack is better than no information, which is what most people have.

So, You Don’t Think JavaScript is “Real” Code?

I had been mulling over this idea for a long time, when, a few years back, I realized that I was making a huge mistake in my approach to JavaScript. You should take it just as seriously as Java, C# or Ruby.

Diseases are something you pick up, JavaScript is something you have to learn.

Just like other programming languages, you need a book, programming exercises and multiple projects. JavaScript also needs coding style guides, testing frameworks, and code analysis, and so on. Basically everything that you have a "real code". There are complete solutions like Yeoman and JHipster that will help you with full integration.

Unless you do this, you will always end up hating JavaScript - which is a shame considering that JavaScript is all around you! If you follow best practices, most of the time you won't be debugging any code nor resorting to clever tricks. Unless you’re Chuck, that is.

More Resources:

2015 conference talks

The past 2015 has been very eventful year for me on both professional and private plan. I got married, moved to Sweden, started working f...

Popular posts