ThreadLocal-jdk1.8

ThreadLocal的用處

對(duì)于每一個(gè)ThreadLocal實(shí)例對(duì)象,每個(gè)線程往這個(gè)ThreadLocal中讀寫是線程隔離,互相之間不會(huì)影響的。它提供了一種將可變數(shù)據(jù)通過每個(gè)線程有自己的獨(dú)立副本從而實(shí)現(xiàn)線程封閉的機(jī)制。

Api

image.png

源碼解讀

1.從set方法開始,初始化容器

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

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

      ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

創(chuàng)建一個(gè)ThreadLocalMap對(duì)象,放到當(dāng)前線程里。第一次讀這塊源碼的時(shí)候感覺一下子繞不過來(lái)。舉個(gè)例子來(lái)說明下。

    @Test
    public void testThreadLocal(){
        ThreadLocal<String> t1 = new ThreadLocal<>();
        ThreadLocal<String> t2 = new ThreadLocal<>();
        ThreadLocal<String> t3 = new ThreadLocal<>();
        t1.set("aaa");
        t2.set("bbb");
        t3.set("ccc");
    }

如上,當(dāng)一個(gè)線程執(zhí)行這段代碼,只會(huì)創(chuàng)建一個(gè)ThreadLocalMap對(duì)象放入當(dāng)前線程內(nèi),然后將t1,t2,t3作為key,對(duì)應(yīng)的值作為value放入ThreadLocalMap對(duì)象里。
值的注意的是這里的Entity的key是一個(gè)弱引用

        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

這樣做的意義應(yīng)該是為了gc,因?yàn)槿绻粋€(gè)線程一直存在的話,它所占用的key,即ThreadLocal實(shí)例對(duì)象會(huì)一直不會(huì)被回收。

2.接下來(lái)就是重頭戲了,set的具體過程

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

在這里,可以將tab看成一個(gè)首尾相接的圓環(huán),初始化被分成16等份,編號(hào)從0-15.
進(jìn)行set操作的時(shí)候,先獲取key的hash散列值作為下標(biāo)開始從圓環(huán)上遍歷。

先認(rèn)識(shí)兩個(gè)重要函數(shù)expungeStaleEntrycleanSomeSlots

    private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // staleSlot位置的元素是key為null的entity,也就是弱引用被回收了,這種元素自然要被清理掉的
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // 清理掉之后,如果后面有連續(xù)的不為null的entity,那就要往前挪動(dòng),或者還有弱引用被回收的,也要清理
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

expungeStaleEntry的作用就是清理弱引用被回收的entity以及調(diào)整往后連續(xù)不為null的entity的位置,如果連續(xù)不為null的entity中還有弱引用被回收的,也要清理。

    private boolean cleanSomeSlots(int i, int n) {
            boolean removed = false;
            Entry[] tab = table;
            int len = tab.length;
            do {
                i = nextIndex(i, len);
                Entry e = tab[i];
                if (e != null && e.get() == null) {
                    n = len;
                    removed = true;
                    i = expungeStaleEntry(i);
                }
            } while ( (n >>>= 1) != 0);//個(gè)人感覺這個(gè)操作還是比較魔性的,稱之為啟發(fā)式掃描。。。
            return removed;
        }

cleanSomeSlots啟發(fā)式掃描清理,自行體會(huì)吧。。。

set的第一段代碼邏輯如下:從位置i開始遍歷圓環(huán)
1.entity為null,則直接new復(fù)制,啟發(fā)式掃描,判斷是否觸發(fā)擴(kuò)容
2.entity不為null,且key不為null,key==當(dāng)前key,直接替換value
3.entity不為null,但是key為null,就進(jìn)入弱引用替換邏輯

接下來(lái)分析下弱引用替換部分

private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                       int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            Entry e;

            //這個(gè)主要是向前掃描連續(xù)的entity,如果有被回收的弱引用,則記錄最前面的下標(biāo)(表面上看是為了清理被回收的弱引用,實(shí)際上我不是十分理解他這么做的目的是什么)
            // Back up to check for prior stale entry in current run.
            // We clean out whole runs at a time to avoid continual
            // incremental rehashing due to garbage collector freeing
            // up refs in bunches (i.e., whenever the collector runs).
            int slotToExpunge = staleSlot;
            for (int i = prevIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = prevIndex(i, len))
                if (e.get() == null)
                    slotToExpunge = i;

            //向后掃描連續(xù)不為null的entity,如果找到目標(biāo)key就替換
            // Find either the key or trailing null slot of run, whichever
            // occurs first
            for (int i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();

                // If we find key, then we need to swap it
                // with the stale entry to maintain hash table order.
                // The newly stale slot, or any other stale slot
                // encountered above it, can then be sent to expungeStaleEntry
                // to remove or rehash all of the other entries in run.
                if (k == key) {
                    e.value = value;

                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists
                    if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                    return;
                }

                // If we didn't find stale entry on backward scan, the
                // first stale entry seen while scanning for key is the
                // first still present in the run.
                if (k == null && slotToExpunge == staleSlot)
                    slotToExpunge = i;
            }

            //剛開始看的時(shí)候會(huì)質(zhì)疑這里,因?yàn)橛锌赡艽嬖谕瑯觡ey的entity在后面,但是結(jié)合整個(gè)清理掃描的過程可以確保不會(huì)出現(xiàn)這樣的情況。
            // If key not found, put new entry in stale slot
            tab[staleSlot].value = null;
            tab[staleSlot] = new Entry(key, value);

            // If there are any other stale entries in run, expunge them
            if (slotToExpunge != staleSlot)
                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
        }

1.向前掃描連續(xù)不為null的entity,如果有被回收的弱引用,記錄最前的那個(gè)元素下標(biāo)slotToExpunge
2.如果向后元素不為null,則向后掃描連續(xù)不為null的entity,如果尋到到目標(biāo)key,則替換位置
3.如果向后元素為null,則當(dāng)前位置插入新元素

個(gè)人感覺這個(gè)是比較繞的,也有點(diǎn)抽象,要反復(fù)多看幾遍,一部分一部分理解,最后串起來(lái)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 ThreadLocal很多同學(xué)都搞不懂是什么東西,可以用來(lái)干嘛。但面試時(shí)卻又經(jīng)常問到,所以這次我和大家一起學(xué)...
    liangzzz閱讀 12,650評(píng)論 14 228
  • 本篇文章的主要內(nèi)容如下: 1、Java中的ThreadLocal2、 Android中的ThreadLocal3、...
    Sophia_dd35閱讀 674評(píng)論 0 5
  • 下面我就以面試問答的形式學(xué)習(xí)我們的——ThreadLocal類(源碼分析基于JDK8) 問答內(nèi)容 1、問:Thre...
    Sophia_dd35閱讀 2,152評(píng)論 1 36
  • 該文章屬于Android Handler系列文章,如果想了解更多,請(qǐng)點(diǎn)擊《Android Handler機(jī)制之總目...
    AndyJennifer閱讀 6,781評(píng)論 5 32
  • 一、使用姿勢(shì) 二、數(shù)據(jù)結(jié)構(gòu) 三、源碼分析 四、回收機(jī)制 總結(jié) 一、使用姿勢(shì) 最佳實(shí)踐 在類中定義ThreadLoc...
    原水寒閱讀 1,868評(píng)論 2 8

友情鏈接更多精彩內(nèi)容