之前,在我的印象中,一直以爲ThradLocal的實現是這樣子的,有一個全局Map,然後以線程ID作爲key。但是當深入看源碼的時候,發現並不是這樣子的。ThreadLocal本身並不進行變量副本的存儲,所有變量的副本是存在Thread 對象中的。
Thread對象中有一個變量,該變量類型是ThreadLocal.ThreadLocalMap,明顯是一個Map,以ThreadLocal對key,存儲各種變量副本。
爲什麼要用一個Map呢??因爲ThreadLocal,可能是多個不同的對象,可以存儲不同類型的對象,這些對象都統一放到Thred對象來存儲。
我們再來看看ThreadLocalMap的主要實現代碼
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal> {
/** The value associated with this ThreadLocal. */
Object 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.length MUST always be a power of two.
*/
private Entry[] table;
}
很明顯跟HashMap差不多。通過對key進行哈希,然後數組進行存儲,注意到Entry是繼承WeakReference的,這麼做主要是爲了預付內存泄露。
ThreadLocalMap,在什麼時候進行創建?
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
注意這裏的this對象就是ThredLocal對象。
發散思考?
ThreadLocal會出現內存泄露嗎?
ThradLocal在使用過程需要注意什麼?