????ThreadLocal不是JUC并發(fā)包下工具梭冠,它在java.lang包下面浙踢。多線程訪問(wèn)同一個(gè)共享變量的時(shí)候容易出現(xiàn)并發(fā)問(wèn)題达舒,特別是多個(gè)線程對(duì)一個(gè)變量進(jìn)行寫(xiě)入的時(shí)候瞎访,為了保證線程安全,一般使用者在訪問(wèn)共享變量的時(shí)候需要進(jìn)行額外的同步措施才能保證線程安全性吁恍。ThreadLocal是除了加鎖這種同步方式之外的一種保證一種規(guī)避多線程訪問(wèn)出現(xiàn)線程不安全的方法扒秸,當(dāng)我們?cè)趧?chuàng)建一個(gè)變量后,如果每個(gè)線程對(duì)其進(jìn)行訪問(wèn)的時(shí)候訪問(wèn)的都是線程自己的變量這樣就不會(huì)存在線程不安全問(wèn)題冀瓦。
????如果創(chuàng)建了一個(gè)ThreadLocal變量伴奥,那么訪問(wèn)這個(gè)變量的每個(gè)線程都會(huì)有這個(gè)變量的一個(gè)副本,在實(shí)際多線程操作的時(shí)候翼闽,操作的是自己本地內(nèi)存中的變量拾徙。
????ThreadLocal的線程局部值是由它的靜態(tài)內(nèi)部類ThreadLocalMap維護(hù)的。
知道他的邏輯組成之后感局,直接看源碼.從內(nèi)往外看尼啡,首先看ThreadLocalMap的組成暂衡。
static class ThreadLocalMap {
// Entry是ThreadLocalMap哈希數(shù)組中的元素
// 鍵是ThreadLocal對(duì)象,值是ThreadLocal set的值崖瞭,同時(shí)也是個(gè)弱引用
// entry.get()=null 的時(shí)候意味著Entry不再引用該鍵
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
// WeakReference的構(gòu)造函數(shù)
super(k);
value = v;
}
}
/**
* 初識(shí)容量必須為2的次冪
*/
private static final int INITIAL_CAPACITY = 16;
/**
* ThreadLocalMap的哈希表狂巢,表的長(zhǎng)度始終是2的次冪
*/
private Entry[] table;
/**
* 哈希表中元素的個(gè)數(shù)
*/
private int size = 0;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
}
我們走一遍使用主流程,構(gòu)造函數(shù)沒(méi)什么好看的了书聚。
/**
* Creates a thread local variable.
* @see #withInitial(java.util.function.Supplier)
*/
public ThreadLocal() {
}
接著set方法
// 將此線程局部變量的當(dāng)前線程副本設(shè)置為指定值
public void set(T value) {
Thread t = Thread.currentThread();
// 獲取當(dāng)前線程綁定的ThreadLocalMap
ThreadLocalMap map = getMap(t);
// 若當(dāng)前線程有綁定ThreadLocalMap唧领,那么用新value覆蓋舊value
if (map != null)
map.set(this, value);
else
// 否則創(chuàng)建ThreadLocalMap
createMap(t, value);
}
// 獲取當(dāng)前線程綁定的ThreadLocalMap
ThreadLocalMap getMap(Thread t) {
// Thread類里面有個(gè)threadLocals屬性就是每個(gè)線程綁定的ThreadLocal.ThreadLocalMap
return t.threadLocals;
}
讓我們進(jìn)到ThreadLocalMap的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.
// 拿到hash表并且計(jì)算出當(dāng)前key的hash值和HashMap很像
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
// 遍歷hash表找到對(duì)應(yīng)的key,用新值替換舊值
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
// 找到key了用新值替換舊值
if (k == key) {
e.value = value;
return;
}
//若當(dāng)前key不再被引用了雌续,就清除和占用該過(guò)期槽
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
// 沒(méi)有找到對(duì)應(yīng)的key斩个,那么在計(jì)算的索引位置新建hash表中的元素Entry
tab[i] = new Entry(key, value);
int sz = ++size;
//當(dāng)清理成功同時(shí)到達(dá)閾值,需要擴(kuò)容
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
set方法的主流程完事了驯杜,我們看下get方法
public T get() {
// 獲取當(dāng)前線程綁定的ThreadLocalMap
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
// 用當(dāng)前ThreadLocal,也就是key獲取值Entry受啥,然后返回Entry中的值
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
// 若當(dāng)前線程沒(méi)有綁定ThreadLocalMap,那么初始化一個(gè),并返回值
return setInitialValue();
}
// 為當(dāng)前線程初始化一個(gè)ThreadLocalMap艇肴,并返回值
private T setInitialValue() {
T value = initialValue();
// 再次檢驗(yàn)當(dāng)前線程是否綁定ThreadLocalMap
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
protected T initialValue() {
return null;
}
// 為指定線程創(chuàng)建一個(gè)ThreadLocalMap腔呜,指定值,并且綁定到指定線程
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
最后需要看的是remove方法再悼,刪除當(dāng)前線程綁定的ThreadLocalMap中的值
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
// 根據(jù)指定的key(ThreadLocal)核畴,刪除對(duì)應(yīng)的值
private void remove(ThreadLocal<?> key) {
Entry[] tab = table;
int len = tab.length;
// 計(jì)算出下標(biāo)
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
// 遍歷hash表找到對(duì)應(yīng)的key,清除Entry的值
if (e.get() == key) {
e.clear();
expungeStaleEntry(i);
return;
}
}
}
Q:ThreadLocal是怎么實(shí)現(xiàn)線程局部變量的冲九?
A:每個(gè)線程也就是Thread類都有自己的threadLocals屬性谤草,它是ThreadLocal的靜態(tài)內(nèi)部類ThreadLocalMap,在ThreadLocal莺奸,set值和get值的時(shí)候都會(huì)去取當(dāng)前線程的threadLocals屬性丑孩,用threadLocals來(lái)完成set和get操作。每個(gè)Thread的threadLocals都是獨(dú)立的灭贷,他們不共享温学。
Thread的threadLocals屬性定義如下:
ThreadLocal.ThreadLocalMap threadLocals = null;