一、用法:
ThreadLocal用于儲存線程之間的共享變量:對于同一個static ThreadLocal,不同線程隻能從get,set,remove自己的變量,而不會影響其他線程的變量
1.ThreadLocal.get:擷取ThreadLocal中目前線程共享變量的值
2.ThreadLocal.set:設定ThreadLocal中目前線程共享變量的值
3.ThreadLocal.remove:移除ThreadLocal中目前線程共享變量的值
4.ThreadLocal.initialValue:ThreadLocal沒有被目前線程指派值或目前線程remove方法後調用get方法,傳回的值,如果沒有重寫,那麼預設值為null;即get之前必須set,否則就重寫initialValue,否則會報空指針異常
二、原理:
1.get:先擷取到目前線程;再從線程中,取出ThreadLocalMap;如果為空的話,則取預設值;不為空,則用key=ThrealLocal從Map中取出值
2.其中ThreadLocalMap是以Entry作為鍵值對,繼承弱引用;是以存在,當線程沒有結束,但是ThreadLocal已經被回收了,可能導緻線程中存在ThreadLocalMap<null,Object>鍵值對,造成記憶體洩漏。雖然ThreadLocal的get和set方法可以清除ThreadLocalMap中key為null的value,但是get和set方法在記憶體洩漏後,不一定必會調用。是以有這二種處理方式
2.1 使用完線程共享變量後,顯示調用ThreadLocalMap.remove清除線程共享變量
2.2 JDK建議ThreadLocal定義為private static,這樣ThreadLocal的弱引用問題則不存在
三、實作代碼
四、常用場景