Crazy Bob posted on ThreadLocal memory leaks.This type of memory leak really annoys me because I see it very often on Java EE servers and developers are not aware of it.The error is mostly annoying in development, testing environmentswhere the Java EE server is not restarted and the applicationsare just redeployed. Therefore, threads (of thread pools) are not recreated and hold references to old application classes.
My advice is CLEAN YOUR THREADLOCALs
Add a servlet filter, Web frameworkinterceptor or WS handler to set all ThreadLocal variables to null just beforereturning the response to the client. Lower level solutions should be preferred and turn out to be less risky. A dummy implementation (to give an idea) would be a servlet filter:
with a ContextCleaner Interface:
and a dummy implementation:
Where UserSession has static accessors to handle the ThreadLocal and is used by application code to store objects in a ThreadLocal instance:
The problem with this implementation is that it only works with classes that you controland are aware that they use ThreadLocal variables. Maybe with reflection it’s possible to accessthe current Thread’s Map which stores ThreadLocal objects and set them to null one by one. But it would be highly risky if your application server uses ThreadLocal for its own usage.
For further information on ThreadLocal memory leaks see this link