public class Thread implements Runnable { /* 前面略 */ /* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null; /* 後面略 */ }
首先咱們看到的是 Thread 中有一個屬性 threadLocals,它的類型是 ThreadLocalMap,封裝類型是 default(表示它只能在包內可見),jdk 是這麼介紹它的:與此線程有關的 ThreadLocal 值,該映射由 ThreadLocal 類維護。 啥意思呢?那就來看看 ThreadLocalMap 是啥玩意!java
public class ThreadLocal<T> { /* 前面略 */ 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; } } /* 後面略 */ } }
從類定義上能夠看出 ThreadLocal 是支持泛型的,而 ThreadLocalMap 是 ThreadLocal 的一個內部類,封裝類型也是 default(表示只能在包內可見),jdk 是這麼介紹它的:ThreadLocalMap 是自定義的哈希映射,僅適用於維護線程局部值。而且爲了存儲容量可控,不至於內存泄漏,哈希表條目使用弱引用做爲鍵(弱引用的對象的生命週期直到下一次垃圾回收以前被回收),ThreadLocalMap 使用靜態內部類 Entry(能夠類比 Map 中的 entry)來存儲實際的 key 和 value。ide
從上面這些介紹,咱們能夠大體想到,ThreadLocal 是一個與線程相關的類,用來存儲維護線程局部值。this
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
ThreadLocalMap getMap(Thread t) { return t.threadLocals; }
void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
能夠看到 set(T value) 方法作的事情很簡單,就是維護 Thread 的 threadLocals 屬性,若是該屬性不存在的話,就以當前 ThreadLocal 實例爲 key 建立一個;該屬性存在的話,則直接賦值。線程
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 T setInitialValue() { T value = initialValue(); 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; }
get() 的方法一樣很簡單,就是從 Thread 的 threadLocals 屬性獲取值,若是獲取不到,則把 initialValue() 的值賦值給線程的 threadLocals 屬性並返回。initialValue() 方法是一個 protected 類型的方法,默認返回 null,咱們能夠在建立 ThreadLocal 的時候重寫它,表示全部線程的默認值。code
// java8 的方式 ThreadLocal<Boolean> threadLocal1 = ThreadLocal.withInitial(() -> false); // ThreadLocal<Boolean> threadLocal2 = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } };