ThreadLocal源碼解讀

ThreadLocal的作用

用於實現線程內的數據共享,即對於相同的程序代碼,多個模塊在同一個線程中運行時要共享一份數據,而在另外線程中運行時又共享另外一份數據。

 

ThreadLocal的主要方法

主要方法有 get(),set(),remove()

分別對應獲取值,設置值,刪除值

對於同一個線程,在沒有set或remove之後,get會得到null值

 

Thread,ThreadLocal,ThreadLocalMap的關係

實際上,Thread,ThreadLocal,ThreadLocalMap這三個類是協同工作的,先來看看Thread類,也就是大家熟悉的線程類,其內部實際上有一個ThreadLocalMap成員

public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }
    
    ...

    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
    
    ...
}

並且,從定義上可以看出,ThreadLocalMap是ThreadLocal的一個靜態內部類

public class ThreadLocal<T> {

    private final int threadLocalHashCode = nextHashCode();

    /**
     * The next hash code to be given out. Updated atomically. Starts at
     * zero.
     */
    private static AtomicInteger nextHashCode =
        new AtomicInteger();

    // ...這裏省略很多,jdk源碼在將近第300行纔看到ThreadLocalMap的定義,如下

    /**
     * ThreadLocalMap is a customized hash map suitable only for
     * maintaining thread local values. No operations are exported
     * outside of the ThreadLocal class. The class is package private to
     * allow declaration of fields in class Thread.  To help deal with
     * very large and long-lived usages, the hash table entries use
     * WeakReferences for keys. However, since reference queues are not
     * used, stale entries are guaranteed to be removed only when
     * the table starts running out of space.
     */
    static class ThreadLocalMap {
        ...
    }

    ...
}

總的來說,三者關係如下,Thread內部維護一個ThreadLocalMap對象,ThreadLocalMap實現起來實質上是一個哈希表(下面會分析到,其Key值是ThreadLocal對象。

ThreadLocal的get(), set(), remove()方法

get方法如下,首先獲取當前的線程,進而得到該線程所維護的ThreadLocalMap對象,然後ThreadLocal將自己作爲key在map中查詢,如過key查不到值,就調用 setInitialValue 並返回,這方法實質上是填入一個空值

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);    // 這個 this 就是 ThreadLocal 對象自己
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

set方法如下,代碼不多,不過可以看出一點:Thread裏的ThreadLocalMap對象默認是null的,直到你需要使用它

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

remove方法看起來就更簡單了。。。

     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }

ThreadLocalMap源碼分析

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;

        /**
         * The number of entries in the table.
         */
        private int size = 0;

        /**
         * The next size value at which to resize.
         */
        private int threshold; // Default to 0
        
        ...
}

Entry: Entry的目的很明顯,就是以key-value的形式存儲數據,其中key值是ThreadLocal類型,並且Entry以弱引用的形式實現了

INITIAL_CAPACITY: 哈希表初始大小。

table: 這就是個Entry數組,也是哈希表的核心

size: 記錄數據的數量

threshold: 哈希表的門檻值,和rehash有關

 

getEntry()方法,這個方法返回一個Entry給ThreadLocal,ThreadLocal再將Entry的值返回給客戶端

        private Entry getEntry(ThreadLocal<?> key) {
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            if (e != null && e.get() == key)
                return e;
            else
                return getEntryAfterMiss(key, i, e);
        }

一開始會計算哈希值,然後哈希值將直接當做起始查找位置,如果一開始就找到,直接返回,否則觸發getEntryAfterMiss,在分析裏面的邏輯之前先補充一點:ThreadLocalMap內部解決哈希衝突的方法是線性探測法,而不是像HashMap一樣的鏈地址法

接着是getEntryAfterMiss,在某一位置起逐一元素向後檢測,如果能找到key就返回,並且在探測的過程中這個方法還會順便對Map進行“整理”

        private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
            Entry[] tab = table;
            int len = tab.length;

            while (e != null) {
                ThreadLocal<?> k = e.get();
                if (k == key)
                    return e;
                if (k == null)
                    expungeStaleEntry(i);
                else
                    i = nextIndex(i, len);
                e = tab[i];
            }
            return null;
        }

再看看Set方法,線性探測法的思想體現的非常明顯,for循環的過程中,如果找到了匹配的key,替換新值,否則的話,找一塊“空地”,然後把key和value放進這個Entry裏面去

        private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

注意最後兩行,既然是哈希表,數據達到了一定量,當然會觸發rehash,ThreadLocalMap的rehash條件和HashMap類似,HashMap超過了負載因子x數組長度就會觸發rehash。而這裏是size>=threshold會觸發rehash,rehash裏面會調用resize方法,resize大小是原來數組長度的兩倍,然後將threshold設爲新的數組長度

remove方法也一樣,找到了key,然後就進行一些清除工作

        /**
         * Remove the entry for key.
         */
        private void remove(ThreadLocal<?> key) {
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                if (e.get() == key) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章