ThreadLocal詳解(二)

ThreadLocal詳解(二)

上一篇文章講了ThreadLocal的get、set、resize等方法的源碼,但是對於一些單獨的方法例如cleanSomeSlots、expungeStaleEntry並沒有講述,這一節就是要講述這些源碼,在講之前首先提幾個ThreadLocal的注意事項,一般來說就是ThreadLocal如果在使用不當的情況下會出現內存泄漏的問題,其原因就在於如果在線程清除時沒有清除ThreadLocal中的變量,因爲ThreadLocal中的key是當前線程的一個弱引用,此時噹噹前線程結束後,該key就變爲null了,此時ThreadLocalMap中就出現了key爲null,但是value仍然有值的情況,此時就出現了內存泄露。

改進


爲了解決因使用不當可能存在的內存泄漏問題,Doug Lea大師還是做了一些改進來儘可能的避免出現內存泄露,就是方法cleanSomeSlots、expungeStaleEntry、replaceStaleEntry,現在就來看看這三個方法做了哪些措施避免出現內存泄露問題。

replaceStaleEntry


原本準備先說cleanSomeSlots方法,但是在set操作源碼中對於key的處理中,有replaceStaleEntry源碼,因此先說replaceStaleEntry方法,先回到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();
        }

上述for循環插入新值的操作中,最後的if判斷是當value存在值,但是key爲null時進行的value替換操作,這就是在hash碰撞時,遇到髒key的操作,進入到方法replaceStaleEntry中。

/**
         * Replace a stale entry encountered during a set operation
         * with an entry for the specified key.  The value passed in
         * the value parameter is stored in the entry, whether or not
         * an entry already exists for the specified key.
         *
         * As a side effect, this method expunges all stale entries in the
         * "run" containing the stale entry.  (A run is a sequence of entries
         * between two null slots.)
         *
         * @param  key the key
         * @param  value the value to be associated with key
         * @param  staleSlot index of the first stale entry encountered while
         *         searching for key.
         */
        private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                       int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            Entry e;

            // 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;

            // 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;
            }

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

首先看第一個for循環方法。

int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
       (e = tab[i]) != null;
       i = prevIndex(i, len))
       if (e.get() == null)
            slotToExpunge = i;

這個for循環上面有段註解,爲:

// 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).

大致意思就是檢查當前髒key的前後元素,這裏認爲髒key也是成聚集在一起的,如果檢查到髒key,則前置slotToExpunge,最終檢查至沒有未遇到髒key爲止。

同時,在下一段代碼中,該for循環的操作,就是填充這些髒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;
                }

這裏做了一個事情,就是向後環形查找過程中發現key相同的entry就覆蓋並且和髒entry進行交換。

if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
 cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);

上述代碼,如果沒有查找到髒key,就以當前位置作爲起點執行cleanSomeSlots方法。

expungeStaleEntry


在看cleanSomeSlots方法前先看expungeStaleEntry方法,這個方法就比較容易理解了,就是清除髒key。

/**
         * Expunge a stale entry by rehashing any possibly colliding entries
         * lying between staleSlot and the next null slot.  This also expunges
         * any other stale entries encountered before the trailing null.  See
         * Knuth, Section 6.4
         *
         * @param staleSlot index of slot known to have null key
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         */
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            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;
        }

將當前節點key與value均置爲null,便於當前位置放置新的entry,同時該方法還會做一個操作就是往後尋找直到tab[i]爲null爲止,如果在搜索過程中繼續遇到髒key,則繼續執行清除操作。

cleanSomeSlots


現在回頭來看cleanSomeSlots方法。

/**
         * Heuristically scan some cells looking for stale entries.
         * This is invoked when either a new element is added, or
         * another stale one has been expunged. It performs a
         * logarithmic number of scans, as a balance between no
         * scanning (fast but retains garbage) and a number of scans
         * proportional to number of elements, that would find all
         * garbage but would cause some insertions to take O(n) time.
         *
         * @param i a position known NOT to hold a stale entry. The
         * scan starts at the element after i.
         *
         * @param n scan control: {@code log2(n)} cells are scanned,
         * unless a stale entry is found, in which case
         * {@code log2(table.length)-1} additional cells are scanned.
         * When called from insertions, this parameter is the number
         * of elements, but when from replaceStaleEntry, it is the
         * table length. (Note: all this could be changed to be either
         * more or less aggressive by weighting n instead of just
         * using straight log n. But this version is simple, fast, and
         * seems to work well.)
         *
         * @return true if any stale entries have been removed.
         */
        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);
            return removed;
        }

cleanSomeSlots操作就比較簡單了,cleanSomeSlots中n這個參數就是當前tab的長度,然後while循環中進行n >>>= 1,就是一個log2(n),就行log2(n)次循環後,當前清理髒key就結束了。

綜上


threadLocal這一套清理髒key還是挺複雜的,另外也和我們平常認識的有些不同,平常在用時一直以爲此處沒有髒key的處理操作,但現在知道前人對threadLocal還是做了許多優化,而且對以上髒key的處理操作中,並非是能將所有髒key都清理掉,而是在性能和髒key處理上做了一定的折中的選擇,因此在自己平時使用時仍然要避免髒key的出現。

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