Good day everyone,

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.

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).

Since many developers assume that TreadLocal's behavior should be close to Map 
(where a Thread instance is the key) and all of us get used to see that GC 
cleans circular references - I believe that the fix should be applied to the 
issue with ThreadLocal.

Please let me know what do you think of it.

Sincerely Yours,
Victor Polischuk

Reply via email to