Take the 2-minute tour ×

The documentation for org.apache.catalina.core.ThreadLocalLeakPreventionListener says "A LifecycleListener that triggers the renewal of threads in Executor pools when a Context is being stopped to avoid thread-local related memory leaks."

How does it exactly prevent ThreadLocal Memory leaks ? Does it explicitly call ThreadLocal's remove() method when the context is stopped ?

As far as I know, ThreadLocal is implemented as a hash map. The map keys are references to the ThreadLocal instances themselves. The map values are the thread local values.

share|improve this question
Have you tried reading the source? –  Frank Pavageau Feb 14 '13 at 19:54

1 Answer 1

up vote 5 down vote accepted

First some clarification. ThreadLocal leak happens when you place some custom class in ThreadLocal inside your application and you undeploy/redeploy that application without clearing ThreadLocal first. When this happens, thread still holds a reference to your class, which holds a reference to ClassLoader, which in turns holds references to all other classes loaded by your (already undeployed) web application.

And the thread still holds a reference to your object because ThreadLocal values are actually stored inside thread. Failing to clear ThreadLocal means that this particular value will be held by Thread object as long as it's running.

Now back to your question - if you forget to remove some ThreadLocal it will be referenced by pool threads forever. This is what Tomcat is trying to prevent - shutting down and creating new threads if suspecting leak. It's invisible to web applications, but when you stop pool thread and replace it with new one, the old one becomes last object referencing your class, class loader and all other stuff. Finally your ThreadLocal value is eligible for GC.

share|improve this answer
Thanks for the great response Tomasz. I am just curious to know how exactly does tomcat "suspect leak" ? Does it monitor the idle time of thread ? Or monitors if the thread has responded, thrown exception etc ? –  Sumit Feb 14 '13 at 20:16
@Sumit: unfortunately that I don't know. But I suspect that it has to examine all its thread pools and ThreadLocals during undeployment. –  Tomasz Nurkiewicz Feb 14 '13 at 20:20

Your Answer


