本篇文章我來討論一下什麼是ThreadLocal以及它的實現原理。其底層數據結構有點相似HashMap,因此對HashMap不熟悉的朋友能夠先去看一看我前面介紹HashMap的那篇文章。java
本文如如有不對或不實之處,也歡迎各位讀者朋友評論指正,歡迎探討交流。
數組
ThreadLocal提供了線程的局部變量,每一個線程均可以經過set()和get()來對這個局部變量進行操做,但不會和其餘線程的局部變量進行衝突,實現了線程的數據隔離。安全
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;
}
}
//...
}複製代碼
咱們的值都是存儲到這個Map上的,key是當前ThreadLocal對象!數據結構
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}複製代碼
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
複製代碼
/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null複製代碼
在ThreadLoalMap中,也是初始化一個大小16的Entry數組,Entry對象用來保存每個key-value鍵值對,只不過這裏的key永遠都是ThreadLocal對象,經過ThreadLocal對象的set方法,結果把ThreadLocal對象本身當作key,放進了ThreadLoalMap中。併發
public void set(T value) {
// 獲得當前線程對象
Thread t = Thread.currentThread();
// 這裏獲取ThreadLocalMap
ThreadLocalMap map = getMap(t);
// 若是map存在,則將當前線程對象t做爲key,要存儲的對象
//做爲value存到map裏面去
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
private void set(ThreadLocal key, Object value) {
Entry[] tab = table;
int len = tab.length;
//根據hash值計算存放下標i
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();
}
複製代碼
這樣的話,在get的時候,也會根據ThreadLocal對象的hash值,定位到table中的位置,而後判斷該位置Entry對象中的key是否和get的key一致,若是不一致,就判斷下一個位置,能夠發現,set和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();
}
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);
}
//查找對應key的 Entry
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;
} 複製代碼