The documentation for org.apache.catalina.core.ThreadLocalLeakPreventionListener says
A
LifecycleListenerthat triggers the renewal of threads in Executor pools when aContextis 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With