Monday, February 27, 2006

ThreadLocal Memory Leak

ThreadLocal is implemented as a weak hash map. Each thread has a map instance. The map keys are weak references to the ThreadLocal instances themselves. The map values are the thread local values. Just like with WeakHashMap instances, if your value somehow holds a strong reference to the ThreadLocal key, the garbage collector can't reclaim either until you explicitly set the value to null or even better call remove() on the ThreadLocal instance. This bit me in the ass today when I mixed ThreadLocal with nested classes, instances of which have an implicit strong reference to their nesting instance, and failed to properly clean up afterwards. "Implicit" is synonymous with "easy to forget about." Oops.

4 Comments:

Blogger Chad Woolley said...

I never had a good argument for why I don't like inner classes. Now I do!

11:55 PM  
Anonymous Anonymous said...

One point regarding inner classes: this only applies to non-static inner classes. I generally only use static ones, to avoid adding that implicit 'this' reference.

2:06 PM  
Blogger Bob said...

Yeah, I actually meant "inner" as opposed to "nested" class. Thanks for the correction. Also, I did need an inner class in this case.

2:12 PM  
Blogger Ondrej Medek said...

Ping back: http://xmedeko.blogspot.com/2010/02/java-web-container-hunting-redeploy.html

You have helped me to fix leak in JasperReports: http://jasperforge.org/projects/jasperreports/tracker/view.php?id=4768 Thanks.

4:36 AM  

Post a Comment

<< Home