ThreadLocal閱讀

ThreadLocal的實現是通過在線程內部保存了一個map結構,當前線程使用變量時,獲取當前線程內部的map,達到了線程本地變量的目的,下面是對源碼加了一些註釋,有誤請指正。

package com.mr.study.threadlocal;

import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

/**
 * @author zhanxp
 * @version 1.0 2019/8/1
 */
public class MyThreadLocal<T> {
    /**
     * 用於保存該對象的hashCode,通過計算得到,該算法可以很大程度上避免hash衝突
     */
    private final int threadLocalHashCode = nextHashCode();

    /**
     * 下一個ThreadLocal的hash值
     */
    private static AtomicInteger nextHashCode =
            new AtomicInteger();

    /**
     * 每次hash增加的值
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * 獲取下一個hash值
     *
     * @return
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

    /**
     * 在線程沒有初始化值的時候返回的初始值
     *
     * @return
     */
    protected T initialValue() {
        return null;
    }

    /**
     * 通過supplier函數初始化值
     *
     * @param supplier
     * @param <S>
     * @return
     */
    public static <S> MyThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new MyThreadLocal.SuppliedMyThreadLocal<>(supplier);
    }

    /**
     * Creates a thread local variable.
     *
     * @see #withInitial(java.util.function.Supplier)
     */
    public MyThreadLocal() {
    }

    /**
     * 獲取線程本地變量
     *
     * @return
     */
    public T get() {
        //獲取當前線程
        Thread t = Thread.currentThread();
        MyThreadLocal.MyThreadLocalMap map = getMap(t);
        if (map != null) {
            //如果map存在,則直接從map中獲取值
            MyThreadLocal.MyThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T) e.value;
                return result;
            }
        }
        //map不存在或者沒值,返回初始化值
        return setInitialValue();
    }

    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        MyThreadLocal.MyThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *              this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        MyThreadLocal.MyThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    /**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * {@code initialValue} method in the current thread.
     *
     * @since 1.5
     */
    public void remove() {
        MyThreadLocal.MyThreadLocalMap m = getMap(Thread.currentThread());
        if (m != null) {
            m.remove(this);
        }
    }

    /**
     * Get the map associated with a MyThreadLocal. Overridden in
     * InheritableMyThreadLocal.
     *
     * @param t the current thread
     * @return the map
     */
    MyThreadLocal.MyThreadLocalMap getMap(Thread t) {
        //線程內部保存了一個MyThreadLocalMap變量,直接獲取該變量,該變量是該線程獨有的
        return t.threadLocals;
    }

    /**
     * Create the map associated with a MyThreadLocal. Overridden in
     * InheritableMyThreadLocal.
     *
     * @param t          the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new MyThreadLocal.MyThreadLocalMap(this, firstValue);
    }

    /**
     * Factory method to create map of inherited thread locals.
     * Designed to be called only from Thread constructor.
     *
     * @param parentMap the map associated with parent thread
     * @return a map containing the parent's inheritable bindings
     */
    static MyThreadLocal.MyThreadLocalMap createInheritedMap(MyThreadLocal.MyThreadLocalMap parentMap) {
        return new MyThreadLocal.MyThreadLocalMap(parentMap);
    }

    /**
     * Method childValue is visibly defined in subclass
     * InheritableMyThreadLocal, but is internally defined here for the
     * sake of providing createInheritedMap factory method without
     * needing to subclass the map class in InheritableMyThreadLocal.
     * This technique is preferable to the alternative of embedding
     * instanceof tests in methods.
     */
    T childValue(T parentValue) {
        throw new UnsupportedOperationException();
    }

    /**
     * An extension of MyThreadLocal that obtains its initial value from
     * the specified {@code Supplier}.
     */
    static final class SuppliedMyThreadLocal<T> extends MyThreadLocal<T> {

        private final Supplier<? extends T> supplier;

        SuppliedMyThreadLocal(Supplier<? extends T> supplier) {
            this.supplier = Objects.requireNonNull(supplier);
        }

        @Override
        protected T initialValue() {
            return supplier.get();
        }
    }

    /**
     * MyThreadLocalMap is a customized hash map suitable only for
     * maintaining thread local values. No operations are exported
     * outside of the MyThreadLocal 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 MyThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * MyThreadLocal 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<MyThreadLocal<?>> {
            /**
             * The value associated with this MyThreadLocal.
             */
            Object value;

            Entry(MyThreadLocal<?> 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 MyThreadLocal.MyThreadLocalMap.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

        /**
         * Set the resize threshold to maintain at worst a 2/3 load factor.
         */
        private void setThreshold(int len) {
            threshold = len * 2 / 3;
        }

        /**
         * Increment i modulo len.
         */
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

        /**
         * Decrement i modulo len.
         */
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

        /**
         * Construct a new map initially containing (firstKey, firstValue).
         * MyThreadLocalMaps are constructed lazily, so we only create
         * one when we have at least one entry to put in it.
         */
        MyThreadLocalMap(MyThreadLocal<?> firstKey, Object firstValue) {
            table = new MyThreadLocal.MyThreadLocalMap.Entry[INITIAL_CAPACITY];
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new MyThreadLocal.MyThreadLocalMap.Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }

        /**
         * Construct a new map including all Inheritable MyThreadLocals
         * from given parent map. Called only by createInheritedMap.
         *
         * @param parentMap the map associated with parent thread.
         */
        private MyThreadLocalMap(MyThreadLocal.MyThreadLocalMap parentMap) {
            MyThreadLocal.MyThreadLocalMap.Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
            table = new MyThreadLocal.MyThreadLocalMap.Entry[len];

            for (int j = 0; j < len; j++) {
                MyThreadLocal.MyThreadLocalMap.Entry e = parentTable[j];
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    MyThreadLocal<Object> key = (MyThreadLocal<Object>) e.get();
                    if (key != null) {
                        Object value = key.childValue(e.value);
                        MyThreadLocal.MyThreadLocalMap.Entry c = new MyThreadLocal.MyThreadLocalMap.Entry(key, value);
                        int h = key.threadLocalHashCode & (len - 1);
                        while (table[h] != null)
                            h = nextIndex(h, len);
                        table[h] = c;
                        size++;
                    }
                }
            }
        }

        /**
         * 獲取當前本地變量所對應的entry對象
         *
         * @param key
         * @return
         */
        private MyThreadLocal.MyThreadLocalMap.Entry getEntry(MyThreadLocal<?> key) {
            //計算所在數組中的未知
            int i = key.threadLocalHashCode & (table.length - 1);
            MyThreadLocal.MyThreadLocalMap.Entry e = table[i];
            if (e != null && e.get() == key) {
                //如果數組中當前位置的值存在,並且就是該線程變量,則返回當前值
                return e;
            } else {
                //如果當前爲空,或者衝突了,調用該方法找值
                return getEntryAfterMiss(key, i, e);
            }
        }

        /**
         * Version of getEntry method for use when key is not found in
         * its direct hash slot.
         *
         * @param key the thread local object
         * @param i   the table index for key's hash code
         * @param e   the entry at table[i]
         * @return the entry associated with key, or null if no such
         */
        private MyThreadLocal.MyThreadLocalMap.Entry getEntryAfterMiss(MyThreadLocal<?> key, int i, MyThreadLocal.MyThreadLocalMap.Entry e) {
            MyThreadLocal.MyThreadLocalMap.Entry[] tab = table;
            int len = tab.length;

            //如果當前e不爲空,且不是當前值,那麼是hash衝突了,往後找就可以了,如果當前e爲null,則說明不存在當前值,直接返回null
            while (e != null) {
                //獲取threadLocal對象
                MyThreadLocal<?> k = e.get();
                //如果就是當前值,直接返回
                if (k == key) {
                    return e;
                }
                //如果當前k爲空,說明threadLocal已經沒有被引用了,這個時候應該清除k所對應的值,避免內存泄露
                if (k == null) {
                    expungeStaleEntry(i);
                } else {
                    //如果當前k不爲空,並且不是當前值,則繼續往下找
                    i = nextIndex(i, len);
                }
                //當前值等於下一個值
                e = tab[i];
            }
            return null;
        }

        /**
         * Set the value associated with key.
         *
         * @param key   the thread local object
         * @param value the value to be set
         */
        private void set(MyThreadLocal<?> 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.

            MyThreadLocal.MyThreadLocalMap.Entry[] tab = table;
            int len = tab.length;
            //計算ThreadLocal的hash值
            int i = key.threadLocalHashCode & (len - 1);

            //初始化值應該填充再數組i位置,如果值已經存在了,則往下找,直到找到爲空或當前值爲止
            for (MyThreadLocal.MyThreadLocalMap.Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                MyThreadLocal<?> k = e.get();

                //如果key找到,那就直接替換掉當前的值
                if (k == key) {
                    e.value = value;
                    return;
                }

                //如果key爲null,說明threadLocal不在被引用,直接用當前的替換掉就可以了
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            //創建一個新的entry對象,對數組賦值
            tab[i] = new MyThreadLocal.MyThreadLocalMap.Entry(key, value);
            //操作值加1
            int sz = ++size;
            //清除空槽,如果沒有引用被清楚,那麼判斷是否超過容量,超過了需要重新hash
            if (!cleanSomeSlots(i, sz) && sz >= threshold) {
                rehash();
            }
        }

        /**
         * Remove the entry for key.
         */
        private void remove(MyThreadLocal<?> key) {
            MyThreadLocal.MyThreadLocalMap.Entry[] tab = table;
            int len = tab.length;
            //獲取數組中未hash衝突的位置
            int i = key.threadLocalHashCode & (len - 1);
            for (MyThreadLocal.MyThreadLocalMap.Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                //如果找到了當前值,則清空當前值,清空引用
                if (e.get() == key) {
                    e.clear();
                    expungeStaleEntry(i);
                    return;
                }
            }
        }

        /**
         * 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.
         * <p>
         * 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(MyThreadLocal<?> key, Object value,
                                       int staleSlot) {
            MyThreadLocal.MyThreadLocalMap.Entry[] tab = table;
            int len = tab.length;
            MyThreadLocal.MyThreadLocalMap.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;
            //從當前位置往前找,找到數組值爲null後的第一個localThread引用被清除的值
            for (int i = prevIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = prevIndex(i, len)) {
                if (e.get() == null) {
                    slotToExpunge = i;
                }
            }


            //查找當前運行的key或者尾隨的一個空槽,找到就停止
            for (int i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                MyThreadLocal<?> 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];

                    //staleSlot位置保存當前要插入的值
                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists
                    //如果需要清除的是staleSlot,那麼需要清除的下標爲i(因爲值已經發生了互換)
                    if (slotToExpunge == staleSlot) {
                        slotToExpunge = i;
                    }
                    //清除key爲null的引用操作
                    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 MyThreadLocal.MyThreadLocalMap.Entry(key, value);

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

        /**
         * 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) {
            MyThreadLocal.MyThreadLocalMap.Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            //使當前value裏面的值不被引用,可以回收
            tab[staleSlot].value = null;
            //空出數組中的位置
            tab[staleSlot] = null;
            //存在的值減1
            size--;

            // Rehash until we encounter null
            MyThreadLocal.MyThreadLocalMap.Entry e;
            int i;
            //因爲有值被刪除,需要重新計算hash,至到找到數組中的值爲空的爲止
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                MyThreadLocal<?> k = e.get();
                //如果key爲null,則清除引用
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    //如果key不爲null,需要重新計算hash,放到數組中正確的位置
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        //如果算出來的值和i不相等,則把i裏面當前的值清空,然後把當前值填入合適的位置
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        //判斷數組h位置的值是否爲空,如果不爲空,則一直往下找,直到找到爲空爲止
                        while (tab[h] != null) {
                            h = nextIndex(h, len);
                        }
                        //賦值
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

        /**
         * 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;
            MyThreadLocal.MyThreadLocalMap.Entry[] tab = table;
            int len = tab.length;
            //循環找是否存在key爲null,值不爲空的對象,如果存在,則清除
            do {
                i = nextIndex(i, len);
                MyThreadLocal.MyThreadLocalMap.Entry e = tab[i];
                if (e != null && e.get() == null) {
                    n = len;
                    removed = true;
                    i = expungeStaleEntry(i);
                }
            } while ((n >>>= 1) != 0);
            return removed;
        }

        /**
         * Re-pack and/or re-size the table. First scan the entire
         * table removing stale entries. If this doesn't sufficiently
         * shrink the size of the table, double the table size.
         */
        private void rehash() {
            //先清一下所有引用,刪除不必要的內存
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            //如果當前大小超過容量的3/4,則重新調整大小
            if (size >= threshold - threshold / 4) {
                resize();
            }
        }

        /**
         * Double the capacity of the table.
         */
        private void resize() {
            MyThreadLocal.MyThreadLocalMap.Entry[] oldTab = table;
            int oldLen = oldTab.length;
            int newLen = oldLen * 2;
            MyThreadLocal.MyThreadLocalMap.Entry[] newTab = new MyThreadLocal.MyThreadLocalMap.Entry[newLen];
            int count = 0;

            for (int j = 0; j < oldLen; ++j) {
                //獲取舊的值
                MyThreadLocal.MyThreadLocalMap.Entry e = oldTab[j];
                if (e != null) {
                    MyThreadLocal<?> k = e.get();
                    //如果key的引用一句不存在,觸發gc
                    if (k == null) {
                        e.value = null; // Help the GC
                    } else {
                        //否則計算hash值,保存至
                        int h = k.threadLocalHashCode & (newLen - 1);
                        while (newTab[h] != null)
                            h = nextIndex(h, newLen);
                        newTab[h] = e;
                        count++;
                    }
                }
            }

            //調整新的容量
            setThreshold(newLen);
            //初始化新的容量大小
            size = count;
            //初始化新的表大小
            table = newTab;
        }

        /**
         * Expunge all stale entries in the table.
         */
        private void expungeStaleEntries() {
            MyThreadLocal.MyThreadLocalMap.Entry[] tab = table;
            int len = tab.length;
            //遍歷全表,刪除不必要的引用,觸發gc
            for (int j = 0; j < len; j++) {
                MyThreadLocal.MyThreadLocalMap.Entry e = tab[j];
                if (e != null && e.get() == null) {
                    expungeStaleEntry(j);
                }
            }
        }
    }
}

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