看一下源碼上的定義:bash
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code ThreadLocal} instances are typically private
* static fields in classes that wish to associate state with a thread (e.g.,
* a user ID or Transaction ID).
*/
複製代碼
英語比較差勁,湊合翻譯一下,大意是threadLoacl會提供線程局部變量,這些變量不一樣於其餘正常的變量,在每一個線程中都會有一個獨立的副本,能夠經過set和get操做threadLocal中的數據,可是隻會改變本線程中的數據,並不會影響其餘線程;ide
理解起來可能有點繞,看一下代碼,沒有代碼的解釋是沒有靈魂的。。。ui
public static void main(String[] args) {
local=new ThreadLocal<>();
//在主線程中更改變量
local.set("我是main");
System.out.println("main:"+local.get());
//在A線程中程中更改變量
new Thread("ThreadA"){
@Override
public void run() {
super.run();
local.set("我是ThreadA");
System.out.println("ThreadA:"+local.get());
}
}.start();
//在B線程中程中未對變量進行操做,也沒有初始化
new Thread("ThreadB"){
@Override
public void run() {
super.run();
System.out.println("ThreadB:"+local.get());
}
}.start();
}
複製代碼
看一下打印的結果:this
System.out: main:我是main
System.out: ThreadA:我是ThreadA
System.out: ThreadB:null
複製代碼
從結果來分析,上面那段註釋就很好理解了,main、threadA、threadB 三個線程中都擁有一個不一樣的副本,能夠經過set和get方法對本線程中的變量進行操做,並不會影響到其餘線程的變量;spa
咱們從源碼裏面來分析一下:線程
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
if (k == key) {
e.value = value;
return;
}
if (k == null) {
//若是k==null,刪除value的引用,防止泄露
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
複製代碼
ThreadLocalMap 的源碼並不複雜,我這裏只看一些比較重要的方法,省略一些無用的代碼,從上述代碼能夠看出來threadLocalMap用Entry類來進行存儲,以ThreadLocal 做爲key;在經過set方法或者構造方法進行賦值儲存。在set方法裏面每次調用都會檢查一遍數據,而且會清除key爲null的value翻譯
注意: ThreadLocalMap使用ThreadLocal的弱引用做爲key,若是一個ThreadLocal沒有外部強引用來引用它,那麼系統 GC 的時候,這個ThreadLocal勢必會被回收,可是ThreadLocalMap的生命週期卻和Thread同樣長,這樣一來,ThreadLocalMap中就會出現key爲null的Entry,就沒有辦法訪問這些key爲null的Entry的value,若是當前線程再遲遲不結束的話,這些key爲null的Entry的value就會一直存在一條強引用鏈:Thread -> ThreaLocalMap -> Entry -> value永遠沒法回收,形成內存泄漏。在set方法裏面每次調用都會檢查一遍,而且會清除key爲null的value,可是最後一次set的值始終會存在,被回收的時候仍是有泄露的可能,若是想避免此處泄露,就須要手動調用ThreadLocalMap的remove()方法code
構造方法裏面並無進行任何操做,咱們直接從set方法開始:orm
public void set(T value) {
Thread t = Thread.currentThread();
//獲取到當前線程中維護的ThreadLocalMap
ThreadLocalMap map = getMap(t);
if (map != null)
//以ThreadLocal爲key將鍵值對進行儲存
map.set(this, value);
else
//初始化並儲存value
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
複製代碼
set方法很簡單,獲取到當前線程中維護的 ThreadLocalMap,若是還沒有初始化,就調用createMap()方法來進行初始化,並以當前的threadLocal爲key進行儲存生命週期
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
複製代碼
能夠看出來,get方法也是很是簡單的,僅僅是從ThreadLocalMap中取出當前線程的數據,而且在未進行初始化的時候,初始化ThreadLocalMap;setInitialValue方法則是初始化map和設置默認值的方法,能夠看到,getMap獲取到的 ThreadLocalMap 爲空,或者當前線程還沒有賦值的時候,會在setInitialValue方法中經過initialValue()獲取到默認值,initialValue()默認值爲null,咱們能夠經過重寫該方法來修改默認值;