ThreadLocals are a great way of creating per-thread-singletons. I have used it earlier for storing hibernate sessions and it worked perfectly.
For people looking at introductory articles on ThreadLocal, this might be a good resource.
But today I came across an issue that was caused by improper ThreadLocal usage. On a server that uses Thread Pool, when using ThreadLocal, we must make sure that ThreadLocal variables are initialized properly and cleaned up at the end of processing. My expectation was that ThreadLocal.get will return a null when a it is called without proper initialization. But, to my surprise, it was returning some reference to an old object. How ??? B’cose Threads are pooled on this server and it was returning the old object reference stored by some other request.
So the learning is,
ThreadLocal usage is like malloc usage in C, you are responsible for cleaning up your mess. Make sure that, for each fresh request, you always do a set on ThreadLocal before calling get. Also, make sure that you clean up the ThreadLocal variable at the end of each request.
How do you clean up ? Just set it to null, for ex:
LocaleContextHolder.setLocaleContext(null);
Following blogs have good discussions about this issue.
Billy Newport’s Blog
Alef Arendsen’s blog
Again, its perfectly ok to use ThreadLocal in your applications, but follow the initialization and cleanup rule stated above.





