[concurrency-interest] Threadlocals and memory leaks in J2EE

Bob Lee crazybob at crazybob.org
Tue Oct 9 19:51:16 EDT 2007


I just mean that in most use cases, you only need the thread local value set
for a specific scope. This code will never leak:

try {
  threadLocal.set(...);
  doSomething();
} finally {
  threadLocal.remove();
}

Josh's examples #1 and #3 fall into this category. I actually blogged about
some related patterns awhile back:
http://crazybob.org/2006/07/hard-core-java-threadlocal.html

Josh's example #2 poses a bit of a problem, but I've only ever used this
pattern for DateFormat objects, and DateFormat is loaded by the system
classloader, so memory leaks aren't an issue.

Bob

On 10/9/07, David Holmes <dcholmes at optusnet.com.au> wrote:
>
>  A finally block of what?
>
> David
>
> -----Original Message-----
> *From:* crazyboblee at gmail.com [mailto:crazyboblee at gmail.com]*On Behalf Of
> *Bob Lee
> *Sent:* Wednesday, 10 October 2007 9:13 AM
> *To:* dholmes at ieee.org
> *Cc:* Endre Stolsvik; concurrency-interest at cs.oswego.edu
> *Subject:* Re: [concurrency-interest] Threadlocals and memory leaks in
> J2EE
>
> That said, the solution is simply to remove() your thread local values in
> a finally block.
>
> Bob
>
> On 10/9/07, Bob Lee < crazybob at crazybob.org> wrote:
> >
> > On 10/9/07, David Holmes <dcholmes at optusnet.com.au> wrote:
> > >
> > > I am missing something here. I don't see how the old way
> > > (per-Variable:
> > > Thread->value) is different, in terms of retention, to the new way
> > > (per-Thread: variable->value). Can you clarify the problem - thanks.
> >
> >
> > David,
> >
> > With the new model, as you know, Thread keeps a weak reference to the
> > ThreadLocal (key) and a strong reference to the value. If the value
> > inadvertently strongly references the ThreadLocal key, the entry will never
> > get cleaned up. A similar situation could arise in the old model if a value
> > strongly referenced the Thread.
> >
> > It's very easy to accidentally create a strong reference between your
> > value and ThreadLocal instance. For example, say we have classes Foo and Bar
> > which are both loaded by MyClassLoader:
> >
> > class Foo {
> >   static ThreadLocal<Bar> localBar = ...;
> > }
> >
> > That code has a memory leak. If you get rid of all references to
> > MyClassLoader, it and all its classes should get GCed, but in this case, we
> > leak a strong reference:
> >
> >   Thread -> Bar (localBar's value) -> MyClassLoader (Bar.getClass()) ->
> > Foo -> localBar
> >
> > I also ran into this once when I inadvertently created a circular
> > reference by using an inner class:
> > http://crazybob.org/2006/02/threadlocal-memory-leak.html
> >
> > Thanks,
> > Bob
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20071009/ba6dd351/attachment.html 


More information about the Concurrency-interest mailing list