ThreadLocal可以用于存儲每個線程中跨方法使用的數據,具體使用場景如,多數據源標志,session存儲等。
那么到底是如何實現從可以保證Threadlocal中的值,其他線程無法訪問到。
每個線程Thread對象中都存在一個threadLocals屬性,用于存放屬于本線程的ThreadLocal數據,具體定義如下(Thread.class):
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
// 此處未使用private修飾,權限屬于友緣,同時也無法被其他線程對象訪問到,由于Thread.class 與ThreadLocal同屬java.lang包,故而后面創建ThreadLocalMap 可以進行賦值。
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap定義:
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
//key 是ThreadLocal ,且為弱引用,弱引用在GC時會被線程回收,
//作用:當threadlocal強引用不存在后,entry中的key即threadlocal對象,會在GC時被回收,這時對應entry中key即為空,而在get/set方法,具體見 expungeStaleEntry/replaceStaleEntry 時,會清空這些key,從而放置內存泄露。
// 場景示意如下:
//ThreadLocal<String> local = new ThreadLocal<>();
// local.set("123");
//local = null 這時 local強引用失效,即便沒有調用remove方法,對應的value也會清楚掉
//注意:弱引用是指著弱引用指向的對象在沒有其他強引用的情況下,他所指向的引用對象對象被回收掉。
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中的一樣用于存儲數據
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table. table的大小
*/
private int size = 0;
設置get方法
public void set(T value) {
Thread t = Thread.currentThread();
//獲取當前線程的threadLocals
ThreadLocalMap map = getMap(t);
if (map != null)
//存在放置放置到當前線程的threadLocals對象里,此處set邏輯與hashmap相似,不做深究
map.set(this, value);
else
//不存在創建
createMap(t, value);
}
//獲取當前線程的threadLocals
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
//創建threadLocalMap并賦值給當前線程的threadLocals
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
讀取
public T get() {
//與設置相同
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;
}
}
//不存在的話,設置初始值null
return setInitialValue();
}
通過以上代碼閱讀可以發現,每個線程中都存在一個threadLocals ,而threadLocal中的值獲取時,通過當前線程中的ThreadLocalMap 獲取,從而保證獲取的值屬于當前線程。