Using a ThreadLocal in a web application (WAR) may simplify the development, but one must have a very deep understanding of the web container (e.g. Tomcat) internals and Java class loading to avoid memory leaks when WAR is redeployed. See
- Problem with static ThreadLocal: http://blog.arendsen.net/index.php/2005/02/22/threadlocals-and-memory-leaks-revisited/ and once more at http://www.jroller.com/tackline/entry/fixing_threadlocal.
- Problem with inner classes and ThreadLocal: http://crazybob.org/2006/02/threadlocal-memory-leak.html.
The problem might be hidden deep in any library used by the application. To check, if the redeploy memory leak occurs is simple with Eclipse Memory Analyzer (MAT). Just redeploy the WAR several times, make a heap dump (e.g. by jmap
or jconsole
). Then open the heap dump in MAT and click the link Duplicate Classes: List classes loaded by more than one class loader. If there are some duplicated classes, then you have a memory leak.
Tip: how to clean ThreadLocals in a servlet: http://www.dewavrin.info/?p=196