Pages

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:

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

    ReplyDelete
  2. Anonymous2:06 PM

    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.

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

    ReplyDelete
  4. 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.

    ReplyDelete