ThreadLocal

原文鏈接,ThreadLocal講解

看了一篇文章,講ThreadLocal非常明瞭,ThreadLocal提供了線程的局部變量,每個線程都可以通過set()和get()來對這個局部變量進行操作,但不會和其他線程的局部變量進行衝突,實現了線程的數據隔離,也就是說ThreadLocal中set的變量是屬於當前線程的,該變量對其他線程而言是隔離的,不可見的。

ThreadLocal底層維護了一個ThreadLocalMap,key是當前線程的對象Thread.currentThread();來獲取的,value存放創建的當前線程的本地變量

public void set(T value) {
        // 得到當前線程對象
        Thread t = Thread.currentThread();

        // 這裏獲取ThreadLocalMap
        ThreadLocalMap map = getMap(t);

        // 如果map存在,則將當前線程對象t作爲key,要存儲的對象作爲value存到map裏面去
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
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;
            }
        }
        //....很長
}

通過上面我們可以發現的是ThreadLocalMap是ThreadLocal的一個內部類。用Entry類來進行存儲,我們的值都是存儲到這個Map上的,key是當前ThreadLocal對象!

如果該Map不存在,則初始化一個:

void createMap(Thread t, T firstValue) {
    t.threadLocals = new ThreadLocalMap(this, firstValue);
}

如果該Map存在,則從Thread中獲取!

/**
 * Get the map associated with a ThreadLocal. Overridden in
 * InheritableThreadLocal.
 *
 * @param  t the current thread
 * @return the map
 */
ThreadLocalMap getMap(Thread t) {
    return t.threadLocals;
}

Thread維護了ThreadLocalMap變量

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

從上面又可以看出,ThreadLocalMap是在ThreadLocal中使用內部類來編寫的,但對象的引用是在Thread中!

於是我們可以總結出:Thread爲每個線程維護了ThreadLocalMap這麼一個Map,而ThreadLocalMap的key是LocalThread對象本身,value則是要存儲的對象

下面是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();
    }

ThreadLocal原理總結

每個Thread維護着一個ThreadLocalMap的引用

ThreadLocalMap是ThreadLocal的內部類,用Entry來進行存儲

調用ThreadLocal的set()方法時,實際上就是往ThreadLocalMap設置值,key是ThreadLocal對象,值是傳遞進來的對象

調用ThreadLocal的get()方法時,實際上就是往ThreadLocalMap獲取值,key是ThreadLocal對象

ThreadLocal本身並不存儲值,它只是作爲一個key來讓線程從ThreadLocalMap獲取value。

正因爲這個原理,所以ThreadLocal能夠實現“數據隔離”,獲取當前線程的局部變量值,不受其他線程影響~

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