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
Memory leak is caused when ThreadLocal is always existing. If ThreadLocal object could be GC, it will not cause memory leak. Because the entry in ThreadLocalMap extends WeakReference, the entry will be GC after ThreadLocal object is GC.
Below code create a lot of ThreadLocal and it never Memory leak and the thread of main is always live.
// -XX:+PrintGCDetails -Xms100m -Xmx100m
public class Test {
public static long total = 1000000000;
public static void main(String[] args) {
for(long i = 0; i < total; i++) {
// give GC some time
if(i % 10000 == 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ThreadLocal<Element> tl = new ThreadLocal<>();
tl.set(new Element(i));
}
}
}
class Element {
private long v;
public Element(long v) {
this.v = v;
}
public void finalize() {
System.out.println(v);
}
}