ThreadLocal & Memory Leak

前端 未结 7 1281
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条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 10:15

    Below code, the instance t in the for iteration can not be GC. This may be a example of ThreadLocal & Memory Leak

    public class MemoryLeak {
    
        public static void main(String[] args) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 100000; i++) {
                        TestClass t = new TestClass(i);
                        t.printId();
                        t = null;
                    }
                }
            }).start();
        }
    
    
        static class TestClass{
            private int id;
            private int[] arr;
            private ThreadLocal threadLocal;
            TestClass(int id){
                this.id = id;
                arr = new int[1000000];
                threadLocal = new ThreadLocal<>();
                threadLocal.set(this);
            }
    
            public void printId(){
                System.out.println(threadLocal.get().id);
            }
        }
    }
    

提交回复
热议问题