Archive for June, 2006

ThreadLocal is like malloc

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.

Comments (46)

Free servlet hosting

I was looking for a free servlet hosting site and came across this one – myjavaserver. There is an interesting code challenge that you need to pass before you can signup. The best thing is that, you can submit the code online and a unit test will be run immediatly to give the result. This was good chance for me to write some quality java code after a long time :) . Inspite of working at SUN, I write very less amount of code these days.

 myjavaserver supports servlets, jsp and cocoon files. There is Database support (HSQL and InstantDB) and a whole lot of other softwares like Struts, Hibernate etc. 

Comments (5)

My first Blog…

Check out this amazing new browser, Flock. Its based on firefox code base. Have a terrific Look and Feel and amazing tools to upload photos, blog and search.

Blogged with Flock

Leave a Comment