ThreadLocal 源碼解讀

1、引入

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

2、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 建立一個;該屬性存在的話,則直接賦值。線程

3、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 的時候重寫它,表示全部線程的默認值。code

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

4、總結

  • ThreadLocal 用於存儲維護線程的局部值。
  • 和 ThreadLocal 相似的還有一個叫 InheritableThreadLocal, InheritableThreadLocal 繼承自 ThreadLocal,用於父子線程間共享共同的值,父線程中設置的值,子線程中能夠訪問到。
  • 上面看 ThreadLocalMap 的時候,咱們知道 key 是弱引用,gc 的時候 key 會被回收,可是 value 和 ThreadLocalMap 的引用不會被回收,若是這種狀況的 Thread 不少,並且一直沒有執行完,就可能會出現內存泄漏,所以使用完 ThreadLocal 的時候儘可能調用 ThreadLocal 的 remove() 方法。
  • 當使用線程池的時候,在調用 ThreadLocal 的 set 方法後,卻沒有調用 remove 的方法,若是同一個線程再去調用 get 方法可能拿到的值並非當時 set 進去的(由於線程池的線程是複用的),可能致使程序數據異常之類的,所以使用完 ThreadLocal 的時候儘可能調用 ThreadLocal 的 remove() 方法。
相關文章
相關標籤/搜索