ThreadLocal與WeakReference問題

ThreadLocal local = new ThreadLocal();
local.set("當前線程名稱:"+Thread.currentThread().getName());//將ThreadLocal作爲key放入threadLocals.Entry中
Thread t = Thread.currentThread();//注意斷點看此時的threadLocals.Entry數組剛設置的referent是指向Local的,referent就是Entry中的key只是被WeakReference包裝了一下
local = null;//斷開強引用,即斷開local與referent的關聯,但Entry中此時的referent還是指向Local的,爲什麼會這樣,當引用傳遞設置爲null時無法影響傳遞內的結果
System.gc();//執行GC
t = Thread.currentThread();//這時Entry中referent是null了,被GC掉了,因爲Entry和key的關係是WeakReference,並且在沒有其他強引用的情況下就被回收掉了
//如果這裏不採用WeakReference,即使local=null,那麼也不會回收Entry的key,因爲Entry和key是強關聯
//但是這裏僅能做到回收key不能回收value,如果這個線程運行時間非常長,即使referent GC了,value持續不清空,就有內存溢出的風險
//徹底回收最好調用remove
//即:local.remove();//remove相當於把ThreadLocalMap裏的這個元素幹掉了,並沒有把自己幹掉
System.out.println(local);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章