ThreadLocal的用處
對于每一個ThreadLocal實例對象睁冬,每個線程往這個ThreadLocal中讀寫是線程隔離,互相之間不會影響的版姑。它提供了一種將可變數(shù)據(jù)通過每個線程有自己的獨立副本從而實現(xiàn)線程封閉的機制。
Api
源碼解讀
1.從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);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
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);
}
創(chuàng)建一個ThreadLocalMap對象嫁蛇,放到當前線程里。第一次讀這塊源碼的時候感覺一下子繞不過來露该。舉個例子來說明下睬棚。
@Test
public void testThreadLocal(){
ThreadLocal<String> t1 = new ThreadLocal<>();
ThreadLocal<String> t2 = new ThreadLocal<>();
ThreadLocal<String> t3 = new ThreadLocal<>();
t1.set("aaa");
t2.set("bbb");
t3.set("ccc");
}
如上,當一個線程執(zhí)行這段代碼,只會創(chuàng)建一個ThreadLocalMap對象放入當前線程內(nèi)抑党,然后將t1,t2,t3作為key包警,對應的值作為value放入ThreadLocalMap對象里。
值的注意的是這里的Entity的key是一個弱引用
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
這樣做的意義應該是為了gc底靠,因為如果一個線程一直存在的話害晦,它所占用的key,即ThreadLocal實例對象會一直不會被回收暑中。
2.接下來就是重頭戲了篱瞎,set的具體過程
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();
}
在這里,可以將tab看成一個首尾相接的圓環(huán)痒芝,初始化被分成16等份俐筋,編號從0-15.
進行set操作的時候,先獲取key的hash散列值作為下標開始從圓環(huán)上遍歷严衬。
先認識兩個重要函數(shù)
expungeStaleEntry
和cleanSomeSlots
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// staleSlot位置的元素是key為null的entity澄者,也就是弱引用被回收了,這種元素自然要被清理掉的
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// 清理掉之后请琳,如果后面有連續(xù)的不為null的entity粱挡,那就要往前挪動,或者還有弱引用被回收的俄精,也要清理
Entry e;
int i;
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
expungeStaleEntry
的作用就是清理弱引用被回收的entity以及調(diào)整往后連續(xù)不為null的entity的位置询筏,如果連續(xù)不為null的entity中還有弱引用被回收的,也要清理竖慧。
private boolean cleanSomeSlots(int i, int n) {
boolean removed = false;
Entry[] tab = table;
int len = tab.length;
do {
i = nextIndex(i, len);
Entry e = tab[i];
if (e != null && e.get() == null) {
n = len;
removed = true;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);//個人感覺這個操作還是比較魔性的嫌套,稱之為啟發(fā)式掃描。圾旨。踱讨。
return removed;
}
cleanSomeSlots
啟發(fā)式掃描清理,自行體會吧砍的。痹筛。。
set的第一段代碼邏輯如下:從位置i開始遍歷圓環(huán)
1.entity為null廓鞠,則直接new復制帚稠,啟發(fā)式掃描,判斷是否觸發(fā)擴容
2.entity不為null床佳,且key不為null滋早,key==當前key,直接替換value
3.entity不為null夕土,但是key為null馆衔,就進入弱引用替換邏輯
接下來分析下弱引用替換部分
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
//這個主要是向前掃描連續(xù)的entity瘟判,如果有被回收的弱引用,則記錄最前面的下標(表面上看是為了清理被回收的弱引用角溃,實際上我不是十分理解他這么做的目的是什么)
// Back up to check for prior stale entry in current run.
// We clean out whole runs at a time to avoid continual
// incremental rehashing due to garbage collector freeing
// up refs in bunches (i.e., whenever the collector runs).
int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
//向后掃描連續(xù)不為null的entity,如果找到目標key就替換
// Find either the key or trailing null slot of run, whichever
// occurs first
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
// If we find key, then we need to swap it
// with the stale entry to maintain hash table order.
// The newly stale slot, or any other stale slot
// encountered above it, can then be sent to expungeStaleEntry
// to remove or rehash all of the other entries in run.
if (k == key) {
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
if (slotToExpunge == staleSlot)
slotToExpunge = i;
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
// If we didn't find stale entry on backward scan, the
// first stale entry seen while scanning for key is the
// first still present in the run.
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
//剛開始看的時候會質(zhì)疑這里拷获,因為有可能存在同樣key的entity在后面,但是結(jié)合整個清理掃描的過程可以確保不會出現(xiàn)這樣的情況减细。
// If key not found, put new entry in stale slot
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
1.向前掃描連續(xù)不為null的entity匆瓜,如果有被回收的弱引用,記錄最前的那個元素下標slotToExpunge
2.如果向后元素不為null未蝌,則向后掃描連續(xù)不為null的entity驮吱,如果尋到到目標key,則替換位置
3.如果向后元素為null萧吠,則當前位置插入新元素
個人感覺這個是比較繞的左冬,也有點抽象,要反復多看幾遍纸型,一部分一部分理解拇砰,最后串起來。