It is mentioned at multiple posts: improper use of ThreadLocal
causes Memory Leak. I am struggling to understand how Memory Leak would happen using Thread
Here is an alternative to ThreadLocal that doesn't have the memory leak problem:
class BetterThreadLocal {
Map map = Collections.synchronizedMap(new WeakHashMap());
A get() {
ret map.get(Thread.currentThread());
}
void set(A a) {
if (a == null)
map.remove(Thread.currentThread());
else
map.put(Thread.currentThread(), a);
}
}
Note: There is a new memory leak scenario, but it is highly unlikely and can be avoided by following a simple guide line. The scenario is keeping a strong reference to a Thread object in a BetterThreadLocal.
I never keep strong references to threads anyways because you always want to allow the thread to be GC'd when its work is done... so there you go: a memory leak-free ThreadLocal.
Someone should benchmark this. I expect it to be about as fast as Java's ThreadLocal (both essentially do a weak hash map lookup, just one looks up the thread, the other the ThreadLocal).
Sample program in JavaX.
And a final note: My system (JavaX) also keeps track of all WeakHashMaps and cleans them up regularly, so the last super-unlikely hole is plugged (long-lived WeakHashMaps that are never queried, but still have stale entries).