下面我們來(lái)說(shuō)一下ThreadLocal槐雾。我們知道砌们,ThreadLocal是一個(gè)實(shí)現(xiàn)線(xiàn)程間資源隔離的類(lèi)赤嚼,ThreadLocal為變量在每個(gè)線(xiàn)程中都創(chuàng)建了一個(gè)副本旅薄,所以每個(gè)線(xiàn)程可以訪(fǎng)問(wèn)自己內(nèi)部的副本變量辅髓,不同線(xiàn)程之間不會(huì)互相干擾。下面我們就來(lái)看一下ThreadLocal的原理。
我們看一下get方法
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();
}
ThreadLocal有一個(gè)內(nèi)部類(lèi)ThreadLocalMap洛口,這個(gè)類(lèi)有2個(gè)屬性矫付,一個(gè)是size,就是數(shù)組的長(zhǎng)度第焰,一個(gè)是threshold买优,就是擴(kuò)容時(shí)的比例,默認(rèn)是2/3挺举。當(dāng)size >= threshold時(shí)杀赢,遍歷table并刪除key為null的元素,如果刪除后size >= threshold*3/4時(shí)豹悬,需要對(duì)table進(jìn)行擴(kuò)容葵陵。
再來(lái)看一下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);
}
就是每一個(gè)線(xiàn)程都有一個(gè)自己的ThreadLocalMap液荸,每次從自己線(xiàn)程的ThreadLocalMap里取值瞻佛。我們?cè)賮?lái)看一下ThreadLocalMap這個(gè)類(lèi)
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)部維護(hù)了一個(gè)Entry數(shù)組
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
通過(guò)hashcode&(len-1)取到數(shù)組的下標(biāo)值,然后判斷該位置上是否有元素娇钱,如果沒(méi)有直接放入伤柄,如果有,線(xiàn)性找到下一個(gè)位置放入文搂,然后把size++适刀。再來(lái)看一下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();
}
1.先通過(guò)hashcode&(len-1)找到數(shù)組的下標(biāo)
2.如果entry不為null,設(shè)置entry的引用為k
3.如果k==key,則修改value值
4.如果k==null煤蹭,說(shuō)明k是以前的元素笔喉,則刪除原來(lái)的元素,并添加新的元素進(jìn)去硝皂,否則查找下一個(gè)元素的位置常挚,重新判斷k的引用是否為null
5.如果entry為null,則把entry加入到table的i位置中
6.通過(guò)cleanSomeSlots刪除原來(lái)的元素稽物,如果table中沒(méi)有元素刪除奄毡,則判斷是否需要進(jìn)行擴(kuò)容
如果table中的元素?cái)?shù)量達(dá)到閾值threshold的3/4,會(huì)進(jìn)行擴(kuò)容操作贝或,下面我們來(lái)看一下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;
}
首先創(chuàng)建了一個(gè)新的table吼过,容量為原來(lái)table大小的2倍。然后復(fù)制原來(lái)table的元素到新的table中咪奖,如果當(dāng)前位置有元素盗忱,則找到下一個(gè)不為空的位置插入進(jìn)去
再看一下getEntry方法
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
if (e != null && e.get() == key)
return e;
else
return getEntryAfterMiss(key, i, e);
}
通過(guò)hashcode&(len-1)找到數(shù)組的下標(biāo),如果該位置不為空并且entry的key和ThreadLocal一致羊赵,則取出對(duì)應(yīng)位置的元素返回趟佃,否則找到下一個(gè)位置
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal<?> k = e.get();
if (k == key)
return e;
if (k == null)
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
下面來(lái)看一下createMap方法
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
就是把自己作為key放到map里了,在getMap方法里取到當(dāng)前線(xiàn)程的ThreadLocalMap
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
ThreadLocal就分析到這里了。