ThreadLocal & Memory Leak

前端 未结 7 1212
Happy的楠姐
Happy的楠姐 2020-11-27 10:08

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

相关标签:
7条回答
  • 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题