Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does tomcat's ThreadLocalLeakPreventionListener do exactly?

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.

like image 983
Sumit Avatar asked Dec 16 '22 14:12

Sumit


1 Answers

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.

like image 83
Tomasz Nurkiewicz Avatar answered Apr 27 '23 00:04

Tomasz Nurkiewicz