天天看點

ThreadLocal 源碼解讀

一、引入

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 是啥玩意!

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。

從上面這些介紹,我們可以大緻想到,ThreadLocal 是一個與線程相關的類,用來存儲維護線程局部值。

二、set(T value) 方法解讀

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 建立一個;該屬性存在的話,則直接指派。

三、get() 方法解讀

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 的時候重寫它,表示所有線程的預設值。

// java8 的方式
    ThreadLocal<Boolean> threadLocal1 = ThreadLocal.withInitial(() -> false);
    // 
    ThreadLocal<Boolean> threadLocal2 = new ThreadLocal<Boolean>() {
        @Override
        protected Boolean initialValue() {
            return false;
        }
    };
           

四、總結

  • ThreadLocal 用于存儲維護線程的局部值。
  • 和 ThreadLocal 類似的還有一個叫 InheritableThreadLocal, InheritableThreadLocal 繼承自 ThreadLocal,用于父子線程間共享共同的值,父線程中設定的值,子線程中可以通路到。
  • 上面看 ThreadLocalMap 的時候,我們知道 key 是弱引用,gc 的時候 key 會被回收,但是 value 和 ThreadLocalMap 的引用不會被回收,如果這種情況的 Thread 很多,而且一直沒有執行完,就可能會出現記憶體洩漏,是以使用完 ThreadLocal 的時候盡量調用 ThreadLocal 的 remove() 方法。
  • 當使用線程池的時候,在調用 ThreadLocal 的 set 方法後,卻沒有調用 remove 的方法,如果同一個線程再去調用 get 方法可能拿到的值并不是當時 set 進去的(因為線程池的線程是複用的),可能導緻程式資料異常之類的,是以使用完 ThreadLocal 的時候盡量調用 ThreadLocal 的 remove() 方法。