ThreadLocal可以用于存儲(chǔ)每個(gè)線程中跨方法使用的數(shù)據(jù)颁糟,具體使用場(chǎng)景如桑谍,多數(shù)據(jù)源標(biāo)志克懊,session存儲(chǔ)等忱辅。
那么到底是如何實(shí)現(xiàn)從可以保證Threadlocal中的值,其他線程無(wú)法訪問(wèn)到谭溉。
每個(gè)線程Thread對(duì)象中都存在一個(gè)threadLocals屬性墙懂,用于存放屬于本線程的ThreadLocal數(shù)據(jù),具體定義如下(Thread.class):
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
// 此處未使用private修飾扮念,權(quán)限屬于友緣损搬,同時(shí)也無(wú)法被其他線程對(duì)象訪問(wèn)到,由于Thread.class 與ThreadLocal同屬java.lang包柜与,故而后面創(chuàng)建ThreadLocalMap 可以進(jìn)行賦值巧勤。
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap定義:
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
//key 是ThreadLocal ,且為弱引用弄匕,弱引用在GC時(shí)會(huì)被線程回收颅悉,
//作用:當(dāng)threadlocal強(qiáng)引用不存在后,entry中的key即threadlocal對(duì)象迁匠,會(huì)在GC時(shí)被回收剩瓶,這時(shí)對(duì)應(yīng)entry中key即為空,而在get/set方法城丧,具體見(jiàn) expungeStaleEntry/replaceStaleEntry 時(shí)延曙,會(huì)清空這些key,從而放置內(nèi)存泄露。
// 場(chǎng)景示意如下:
//ThreadLocal<String> local = new ThreadLocal<>();
// local.set("123");
//local = null 這時(shí) local強(qiáng)引用失效亡哄,即便沒(méi)有調(diào)用remove方法枝缔,對(duì)應(yīng)的value也會(huì)清楚掉
//注意:弱引用是指著弱引用指向的對(duì)象在沒(méi)有其他強(qiáng)引用的情況下,他所指向的引用對(duì)象對(duì)象被回收掉蚊惯。
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16; //
/**
* The table, resized as necessary. //table與hashmap中的一樣用于存儲(chǔ)數(shù)據(jù)
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table. table的大小
*/
private int size = 0;
設(shè)置get方法
public void set(T value) {
Thread t = Thread.currentThread();
//獲取當(dāng)前線程的threadLocals
ThreadLocalMap map = getMap(t);
if (map != null)
//存在放置放置到當(dāng)前線程的threadLocals對(duì)象里愿卸,此處set邏輯與hashmap相似,不做深究
map.set(this, value);
else
//不存在創(chuàng)建
createMap(t, value);
}
//獲取當(dāng)前線程的threadLocals
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//創(chuàng)建threadLocalMap并賦值給當(dāng)前線程的threadLocals
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
讀取
public T get() {
//與設(shè)置相同
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
//獲取entry
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
//不為空返回value
return result;
}
}
//不存在的話截型,設(shè)置初始值null
return setInitialValue();
}
通過(guò)以上代碼閱讀可以發(fā)現(xiàn)趴荸,每個(gè)線程中都存在一個(gè)threadLocals ,而threadLocal中的值獲取時(shí)菠劝,通過(guò)當(dāng)前線程中的ThreadLocalMap 獲取,從而保證獲取的值屬于當(dāng)前線程。