ThreadLocal的整體的結(jié)構(gòu)
可以通過上圖看到韩脏,ThreadLocal內(nèi)部是基于一個(gè)ThreadLocalMap來實(shí)現(xiàn)晌杰,而ThreadLocalMap內(nèi)部又是一個(gè)Entry的數(shù)據(jù)結(jié)構(gòu)。這個(gè)Entry的數(shù)據(jù)結(jié)構(gòu)最終是基于弱引用來使用功炮。我們看源碼的定義溅潜。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
內(nèi)部數(shù)據(jù)結(jié)構(gòu)之間的通信
從圖一,我們知道了ThreadLocal的數(shù)據(jù)結(jié)構(gòu)與內(nèi)部組件薪伏。下面滚澜,我們來看看他的這些內(nèi)部組件是怎么進(jìn)行一個(gè)溝通訪問的。
我們通過看源碼中的get()操作看看大致是一個(gè)怎么的過程嫁怀。
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();
}
我們想一下设捐,Thread都說是線程之間相互隔離的潦牛,那么相互隔離的話,這個(gè)內(nèi)部維護(hù)的數(shù)據(jù)就應(yīng)該是每個(gè)線程他自己所持有的挡育。我們可以看到getMap(t);的實(shí)現(xiàn)證明了我們這個(gè)想法:
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
而Thread的內(nèi)部也剛好維護(hù)了ThreadLocalMap巴碗。
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
所以,我們可以理解成一個(gè)Thread就有個(gè)自己的ThreadMap.而自己維護(hù)自己的數(shù)據(jù)相互獨(dú)立即寒。但是橡淆,這里要注意一點(diǎn),如果在線程中母赵,在創(chuàng)建一個(gè)線程逸爵,這個(gè)時(shí)候,就不能通過ThreadLocal進(jìn)行g(shù)et數(shù)據(jù)了凹嘲,這個(gè)時(shí)候已經(jīng)做了線程之間的切換了师倔,如果想要獲子線程能夠訪問到父線程的數(shù)據(jù),這個(gè)時(shí)候就要使用InheritableThreadLocal這個(gè)繼承的ThreadLocal來操作了周蹭。
OK趋艘,我們通過ThreadLocal的get操作大致明白了他的一個(gè)內(nèi)部數(shù)據(jù)之間是怎么一個(gè)聯(lián)系。那么我們?cè)賮砜纯碩hreadLocal的set操作又是怎么做的凶朗。線上源碼:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
private void set(ThreadLocal<?> key, Object value) {
// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.
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) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
set方法的前兩步?jīng)]問題瓷胧,通過當(dāng)前Thread獲得自己的ThreadLocalMap。如果ThreadLocalMap為空就進(jìn)行一個(gè)創(chuàng)建棚愤,非空就是一個(gè)填值搓萧。而create的時(shí)候就是簡(jiǎn)單的new ThreadLocalMap(), 并且這個(gè)時(shí)候是綁定當(dāng)前線程的value為一個(gè)null,然后賦值給當(dāng)前ThreadLocal宛畦。
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
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);
}
ThreadLocalMap并不像我們平常使用的HashMap那樣維護(hù)一個(gè)鏈表瘸洛,而是單純的一個(gè)數(shù)組。而他的hashCode是從0x61c88647開始次和,沒使用一次反肋,進(jìn)行一個(gè)加1. 將我們的key 和value維護(hù)到了Entry中,然后在放入我們的Entry數(shù)組中斯够。并記錄ThreadLocalMap的擴(kuò)容閾值囚玫。由于他是使用了一個(gè)AtomicInteger的getAndAdd方法來獲取hashCode,所以读规,我們想的hash沖突就迎刃而解了抓督。
那么我們重點(diǎn)來關(guān)注他下面的set方法。
這個(gè)過程中束亏。通過hash值算出在ThreadLocalMap中的table中的具體下標(biāo)索引铃在。
這里的大致過程就是通過key去尋找對(duì)應(yīng)的Entry是否存在。這里為什么要這么做?因?yàn)镋ntry使用的是一個(gè)弱引用定铜,弱引用在獲取值的時(shí)候阳液,可能已經(jīng)被上一次GC所回收了值,這個(gè)時(shí)候揣炕,我們就要進(jìn)行一個(gè)重新賦值帘皿。
而這個(gè)地方最有意思的就是在最下面的擴(kuò)容了,因?yàn)榍懊娴馁x值只是一些常規(guī)的操作“有畸陡,覆蓋鹰溜;無,創(chuàng)建”丁恭,并且使用的是一個(gè)弱引用而已曹动,可擴(kuò)容的地方就要再看一看了。
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
cleanSomeSlots這個(gè)地方就是我們前面說的牲览,由于是弱引用墓陈,所以這個(gè)地方,他在進(jìn)行一個(gè)填充值的時(shí)候第献,進(jìn)行了一個(gè)額外的刪除已經(jīng)被GC的Key對(duì)應(yīng)的Value(至于為什么要說是已經(jīng)被GC的Key對(duì)應(yīng)的Value我們下面再說贡必。),這個(gè)動(dòng)作相當(dāng)于是一個(gè)懶式的操作痊硕。
下面我們跟進(jìn)rehash():
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
expungeStaleEntries這個(gè)其實(shí)就是cleanSomeSlots的內(nèi)部實(shí)現(xiàn)赊级,用法不解釋了。而當(dāng)容量大于閾值的3/4的時(shí)候岔绸,就需要resize了。
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null; // Help the GC
} else {
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
從這里可以看到橡伞,他的擴(kuò)容是兩倍兩倍的進(jìn)行擴(kuò)容盒揉,然后將老的數(shù)據(jù)從老的table中拿出,然后重新hash得到一個(gè)新的index兑徘,然后填充到新的table中刚盈。這就是一個(gè)簡(jiǎn)單的兩個(gè)數(shù)組的拷貝,然后重新設(shè)置了一下閾值挂脑。好吧藕漱,原來就是這么簡(jiǎn)單。崭闲。肋联。。
再談內(nèi)存泄漏的問題
從第一張圖中刁俭,我們知道了ThreadLocalMap中的內(nèi)部是一個(gè)Entry的數(shù)據(jù)結(jié)構(gòu)橄仍,而Entry的數(shù)據(jù)結(jié)構(gòu)又是一個(gè)弱引用WeakReference<ThreadLocal<?>>.這里要注意了, 弱引用里面的泛型是ThreadLocal,而這個(gè)從之前的代碼里面可以發(fā)現(xiàn),傳遞到這里的ThreadLocal就是this,再結(jié)合一下弱引用的特性想一下侮繁,如果ThreadLocal這個(gè)對(duì)象被回收了虑粥,但是我當(dāng)前的線程還是在繼續(xù)運(yùn)行,注意哦宪哩,我們的ThreadLocalMap是在線程Thread里面的哦娩贷,所以ThreadLocal在弱引用的時(shí)候被GC,我們的線程還在繼續(xù)運(yùn)行锁孟,ThreadLocalMap也是還會(huì)繼續(xù)存活的育勺,但是,這個(gè)時(shí)候罗岖,TheadLocalMap的key已經(jīng)不存在了, 但是涧至,我們的value可不是WeakReference弱引用,并沒有被GC桑包。這樣南蓬,這個(gè)value只要線程還在繼續(xù)運(yùn)行,就永遠(yuǎn)不會(huì)被GC掉哑了。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
所以赘方,這就出現(xiàn)了內(nèi)存泄漏的現(xiàn)象。避免出現(xiàn)這種現(xiàn)象的方法一般都是在ThreadLocal使用完了之后弱左,進(jìn)行一個(gè)TreadLocal.remove()方法操作窄陡。
總結(jié)
ThreadLocal在面試的過程中也經(jīng)常被問到,這里主要要關(guān)注的就是他的內(nèi)部是一個(gè)怎樣的結(jié)構(gòu)拆火,resize的過程跳夭,內(nèi)存泄漏是怎么發(fā)生(主要結(jié)合弱引用的特性)。