Memory leak in j.l.ThreadLocal

cowwoc cowwoc at bbs.darktech.org
Sat Oct 26 20:54:08 UTC 2013


     I think most of these (and other) problems associated with JavaEE 
would go away if it would adopt the Jetty model: "Don't deploy your 
application in Jetty, deploy Jetty in your application."

     I can't begin to explain how many problems went away as soon as I 
made the switch. This is most apparent when dealing with JNI. A JVM may 
not load the same library multiple times, but different webapps often 
need to link to the same library. There are workarounds but they are 
fragile and ugly. Deploying JavaEE inside the application instead of the 
application inside JavaEE works wonders.

     Just my 2 cents.

Gili

On 26/10/2013 1:26 PM, Andrew Haley wrote:
> 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