Memory leak in j.l.ThreadLocal

Andrew Haley aph at redhat.com
Sat Oct 26 17:26:30 UTC 2013


Hi,

On 10/26/2013 03:54 PM, Victor Polischuk wrote:

> There is a quite old problem within ThreadLocal semantic which
> causes memory leak in case an object put in ThreadLocal has hard
> reference (direct or indirect) to ThreadLocal itself. Some
> references can be found:
>  * http://stackoverflow.com/questions/17968803/threadlocal-memory-leak
>  * http://plumbr.eu/blog/how-to-shoot-yourself-in-foot-with-threadlocals
>  * many other sites which consider it as a problem.

I presume you've also read
http://cs.oswego.edu/pipermail/concurrency-interest/2007-October/004456.html

> In a word, since values put in a ThreadLocal are stored not in the
> instance but in a Thread as *hard* references there is no chance the
> instance will be collected unless all threads died (which is not an
> option in case of using a thread pool).
> 
> The most obvious solution is to introduce "ConcurrentWeakHashMap" or
> something like it and store the values in ThreadLocal itself (in the
> case we probably lose performance).
> 
> Another solution: currently, a thread has weak reference to
> ThreadLocal but a strong reference to its value. Let's invert it: a
> weak reference to a ThreadLocalEntry (couple ThreadLocal and value)
> in Thread but ThreadLocal stores a strong reference to
> ThreadLocalEntry. In this case the only synchronized thing we need
> to implement - write-only storage of ThreadLocalEntry in ThreadLocal
> (updates will be done from Thread so no sync needed).

a.  Can you do this without sacrificing performance, and
b.  Can you do this without breaking compatibility?

Andrew.



More information about the core-libs-dev mailing list