ThreadLocal源码解读

/*
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

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

/**
 * This class provides thread-local variables.  These variables differ from
 * their normal counterparts in that each thread that accesses one (via its
 * {@code get} or {@code set} method) has its own, independently initialized
 * copy of the variable.  {@code ThreadLocal} instances are typically private
 * static fields in classes that wish to associate state with a thread (e.g.,
 * a user ID or Transaction ID).
 *
 * <p>For example, the class below generates unique identifiers local to each
 * thread.
 * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
 * and remains unchanged on subsequent calls.
 * <pre>
 * import java.util.concurrent.atomic.AtomicInteger;
 *
 * public class ThreadId {
 *     // Atomic integer containing the next thread ID to be assigned
 *     private static final AtomicInteger nextId = new AtomicInteger(0);
 *
 *     // Thread local variable containing each thread's ID
 *     private static final ThreadLocal&lt;Integer&gt; threadId =
 *         new ThreadLocal&lt;Integer&gt;() {
 *             &#64;Override protected Integer initialValue() {
 *                 return nextId.getAndIncrement();
 *         }
 *     };
 *
 *     // Returns the current thread's unique ID, assigning it if necessary
 *     public static int get() {
 *         return threadId.get();
 *     }
 * }
 * </pre>
 * <p>Each thread holds an implicit reference to its copy of a thread-local
 * variable as long as the thread is alive and the {@code ThreadLocal}
 * instance is accessible; after a thread goes away, all of its copies of
 * thread-local instances are subject to garbage collection (unless other
 * references to these copies exist).
 *
 * @author  Josh Bloch and Doug Lea
 * @since   1.2
 */
public class ThreadLocal<T> {
    /**
     * ThreadLocals rely on per-thread linear-probe hash maps attached
     * to each thread (Thread.threadLocals and
     * inheritableThreadLocals).  The ThreadLocal objects act as keys,
     * searched via threadLocalHashCode.  This is a custom hash code
     * (useful only within ThreadLocalMaps) that eliminates collisions
     * in the common case where consecutively constructed ThreadLocals
     * are used by the same threads, while remaining well-behaved in
     * less common cases.
     */
    private final int threadLocalHashCode = nextHashCode();

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

    /**
     * The difference between successively generated hash codes - turns
     * implicit sequential thread-local IDs into near-optimally spread
     * multiplicative hash values for power-of-two-sized tables.
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * Returns the next hash code.
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

    /**返回此线程局部变量的当前线程的“初始值”
     * Returns the current thread's "initial value" for this thread-local variable.   
	   This method will be invoked the first
	   如果直接调用get方法将会调用该方法,除非之前调用了set方法进行设置值,
	   jdk1.5之后,threadLocal中多了一个remove方法,如果调用remove方法后直接调用get方法,也将会调用该方法
     * time a thread accesses the variable with the {@link #get}
     * method, unless the thread previously invoked the {@link #set}
     * method, in which case the {@code initialValue} method will not
     * be invoked for the thread. 
      通常,每个线程最多调用此方法一次,但在调用remove 方法之后直接调用get方法的情况下可能会再次调用。
 	 Normally, this method is invoked at
     * most once per thread, but it may be invoked again in case of
     * subsequent invocations of {@link #remove} followed by {@link #get}.
     *
	 此实现仅返回 null;如果程序员希望线程局部变量具有 null以外的初始值,
	 则必须对  ThreadLocal 进行子类化,并覆盖此方法。通常,将使用匿名内部类。
     * <p>This implementation simply returns {@code null}; if the
     * programmer desires thread-local variables to have an initial
     * value other than {@code null}, {@code ThreadLocal} must be
     * subclassed, and this method overridden.  Typically, an
     * anonymous inner class will be used.
     *
     * @return the initial value for this thread-local
     */
    protected T initialValue() {
        return null;
    }

    /**
     * Creates a thread local variable. The initial value of the variable is
     * determined by invoking the {@code get} method on the {@code Supplier}.
     *
     * @param <S> the type of the thread local's value
     * @param supplier the supplier to be used to determine the initial value
     * @return a new thread local variable
     * @throws NullPointerException if the specified supplier is null
     * @since 1.8
     */
    public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
        return new SuppliedThreadLocal<>(supplier);
    }

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

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
		//获取当前线程
        Thread t = Thread.currentThread();
		//获取当前线程't'的 默认访问权限的成员变量 'threadLocals'
		/*
		 * 线程Thread中的定义
		 * ThreadLocal.ThreadLocalMap threadLocals = null;
	    */
        ThreadLocalMap map = getMap(t);
		//如果map不为空,即该线程中的threadLocals不为空
        if (map != null) {
			 //以当前的ThreadLocal为key,调用getEntry获取对应的存储实体e
            ThreadLocalMap.Entry e = map.getEntry(this);
			//对e判空
            if (e != null) {
				//如果e不为空,则根据泛型强转值
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
				 //返回该值
                return result;
            }
        }
		//初始化,两种情况执行该代码
        //(1)、当前线程map不存在,即此线程没有维护的ThreadLocalMap
        //(2)、map存在,e为空,即线程有维护的ThreadLocalMap但是此ThreadLocal没有关联的值
        return setInitialValue();
    }

    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *与set方法类似,只是set方法的值是通过参数穿过来的,而这里是通过initialValue方法获取的
     * @return the initial value
     */
	 //初始化,该方法是在ThreadLocal对象没有调用set(),而直接调用get()方法时调用,或者调用remove后直接调用get()方法时调用
    private T setInitialValue() {
		//直接调用方法initialValue,此方法可以被子类重写,如果不重写默认返回null
        T value = initialValue();
		//获取当前线程
        Thread t = Thread.currentThread();
		//获取当前线程't'的 默认访问权限的成员变量 'threadLocals'
		/*
		 * 线程Thread中的定义
		 * ThreadLocal.ThreadLocalMap threadLocals = null;
	    */
        ThreadLocalMap map = getMap(t);
	   //如果map不为空,即该线程中的threadLocals不为空
        if (map != null)
			//通过获取的value值进行覆盖,其实此时的value为 null,this为调用该方法的对象
            map.set(this, value);
        else
			//如果线程't'中的 threadLocals也就是map为空则创建相应的map并赋值
            createMap(t, value);
		//如果以一切正常并且不重写initialValue,则返回value即null值,这样就是为什么在ThreadLocal对象没有调用set(),而直接调用get()方法时,会获取一个null值
        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();
		//获取当前线程't'的 默认访问权限的成员变量 'threadLocals'
		/*
		 * 线程Thread中的定义
		 * ThreadLocal.ThreadLocalMap threadLocals = null;
	    */
        ThreadLocalMap map = getMap(t);
		 //如果map不为空,即该线程中的threadLocals不为空
        if (map != null)
			//通过传过来的value值进行覆盖,this 指的是ThreadLocal的实例
            map.set(this, value);
        else
			//如果为空则创建相应的map并赋值
            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
     */
	 // 删除此线程局部变量的当前线程值。
	 //如果调用remove方法后直接调用get方法, 将通过调用setInitialValue 方法重新初始化,除非调用完remove后又调用了set方法之后再调用get方法。
	 //remove可能会导致在当前线程中多次调用   setInitialValue、initialValue 方法。
     public void remove() {
		 
        //根据当前线程获取map
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
			  //如果map不为空,则根据键(调用此方法的ThreadLocal对象)移除该元素
             m.remove(this);
     }

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
	 /*
	  * 线程Thread中的定义
	  * ThreadLocal.ThreadLocalMap threadLocals = null;
	  */
    ThreadLocalMap getMap(Thread t) {
		//返回线程t对象中的threadLocals成员变量
        return t.threadLocals;
    }

    /**
	 * 创建与 ThreadLocal 关联的映射
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
	 //创建一个新的ThreadLocalMap对象,并把对象赋值给线程t的threadLocals成员变量
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(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 ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
        return new ThreadLocalMap(parentMap);
    }

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

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

        private final Supplier<? extends T> supplier;

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

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

    /**
     * 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 {

        /**
         * 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.
         */
		//定义 Entry 类,该对象继承WeakReference 所以该类属于若引用
        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.
         */
		 //初始容量 -- 必须是 2 的幂
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.   根据需要调整大小。
         * table.length MUST always be a power of two.  table.length 必须始终是 2 的幂。
         */
		 //这个数组 table 就是ThreadLocalMap对象的容器,数据就存放再该数组中
        private Entry[] table;

        /**
         * The number of entries in the table. 
         */
		//变量table 的大小
        private int size = 0;

        /**
         * The next size value at which to resize.
         */
		// table 数组,要调整大小的下一个大小值
        private int threshold; // Default to 0

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

        /**
         * Increment i modulo len.
         */
		//获取i+1,如果i+1>=len,则返回0
		//在此处len指的是数组容量,如果i+1>=数组大小,证明i为该数组的最后一位,所以返回0,也就是循环获取数组的下一个位置
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

        /**
         * Decrement i modulo len.
         */
		 
		//与nextIndex作用正好相反,这个是获取数组前面一个位置
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

        /**
         * Construct a new map initially containing (firstKey, firstValue).
         * ThreadLocalMaps are constructed lazily, so we only create
         * one when we have at least one entry to put in it.
		 构造一个最初包含 (firstKey, firstValue) 的新映射。 ThreadLocalMaps 是惰性构造的,所以我们只有在至少有一个条目可以放入时才创建一个
         */
		//通过key,value创建一个ThreadLocalMap对象
        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
			//创建一个大小为16的Entry数组,并把该数组对象赋值给table引用
            table = new Entry[INITIAL_CAPACITY];
			//获取一个小于16的非负整数(& (INITIAL_CAPACITY - 1))
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
			//根据key,value创建Entry对象,并把该对象放到table数据的i位置
            table[i] = new Entry(firstKey, firstValue);
			//记录table数组使用大小
            size = 1;
		  //设置扩展因子大小 16*2/3 =10
            setThreshold(INITIAL_CAPACITY);
        }

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

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

        /**
         * Get the entry associated with key.  This method
         * itself handles only the fast path: a direct hit of existing
         * key. It otherwise relays to getEntryAfterMiss.  This is
         * designed to maximize performance for direct hits, in part
         * by making this method readily inlinable.
         *
         * @param  key the thread local object
         * @return the entry associated with key, or null if no such
         */
		 //根据key(threadLocal对象)获取相应的value
        private Entry getEntry(ThreadLocal<?> key) {
			//根据key获取相应的数组下标 i
            int i = key.threadLocalHashCode & (table.length - 1);
			//通过下标获取该元素
            Entry e = table[i];
			//判断获取元素是否为空,并且元素的key是否与形参一致
            if (e != null && e.get() == key)
				//如果符合上边的判断则直接返回该元素
                return e;
            else
				//如果不符合(即根据下标获取的元素为空,或者元素的key与形参不一致),则调用getEntryAfterMiss 方法,
                return getEntryAfterMiss(key, i, e);
        }

        /**
         * Version of getEntry method for use when key is not found in
         * its direct hash slot.
         *  在其直接哈希槽中找不到键时使用的getEntry方法的版本。
         * @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
         */
		 //使用getEntry方法,根据key获取相应的数组下标,根据该下标无法直接获取到元素时,使用该方法
        private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
			//把类中的容器数组引用给tab
            Entry[] tab = table;
			//获取数组长度
            int len = tab.length;
            //如果e不为空,则进入循环
            while (e != null) {
                ThreadLocal<?> k = e.get();
				//while循环时,如果查找到数组某个位置的元素的key是 与形参一致,则说明找到该元素,即返回该元素
                if (k == key)
                    return e;
				如果在数组某一个位置,元素不为空,但是key为空则,调用expungeStaleEntry方法,并继续while循环
                if (k == null)
					//该方式就是把这个没有key的元素,清除掉,并把i坐标往后的元素位置进行重新设置。这在在一定程度上能避免内存泄漏
                    expungeStaleEntry(i);
                else
					//获取数组下一个位置,如果i位置为数组最后一个元素对应的坐标,返回0,即
                    i = nextIndex(i, len);
                e = tab[i];
            }
			//无论是getEntry调用该方式时e,为空,还是根据i位置循环查找数组遇到了数组为空的位置时还没有查找到key对应的元素,则直接返回null,
            return null;
        }

        /**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be 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();
        }

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

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

        /**
         * 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).
         */
		 //该方法的作用就是把数组下标:staleSlot 这个位置设为null,
		 //并把staleSlot往后的元素的位置重新进行一个刷新,直到遇到数组位置为空的地方,并把该为为空位置的下标进行一个返回
		 //中途如果遇到某个位置的元素不为空,但该元素的key为空,则也会把该位置置为null,这又在一定程度上避免了内存泄漏
        private int expungeStaleEntry(int staleSlot) {
			//把类中的容器数组引用给tab
            Entry[] tab = table;
			//获取数组长度
            int len = tab.length;

            // expunge entry at staleSlot
			//把数组staleSlot位置上的元素的值设为null,这样对应引用类型对象,可以避免内存泄漏
            tab[staleSlot].value = null;
		    //把数组staleSlot位置设置为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)//获取数组的下一个位置对应的下标值
				 ) {
					 //获取元素的key
                ThreadLocal<?> k = e.get();
				//如果key为空
                if (k == null) {
					//把数组该位置上的元素的值设为null,这样对应引用类型对象,可以避免内存泄漏
                    e.value = null;
					//把数组该位置设置为null
                    tab[i] = null;
					//把该数组元素个数减一
                    size--;
                } else {//如果元素的key不为空
				     //获取该元素key的哈希值,也就是该元素在不发生hash冲突时该放的数组下标
                    int h = k.threadLocalHashCode & (len - 1);
					
                    if (h != i) {//如果不等于i,即说明该位置的元素在存的时候发生了hash冲突
					    //则把该位置设置为null
                        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下标位置为空则直接放到该h位置,如果不为空则继续循环往后找
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
			//返回的i值为数组从staleSlot位置往后的第一个为空的元素的位置下标值
            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;
            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;
        }

        /**
         * 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
            if (size >= threshold - threshold / 4)
                resize();
        }

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

            for (int j = 0; j < oldLen; ++j) {
                Entry e = oldTab[j];
                if (e != null) {
                    ThreadLocal<?> k = e.get();
                    if (k == null) {
                        e.value = null; // Help the GC
                    } else {
                        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() {
            Entry[] tab = table;
            int len = tab.length;
            for (int j = 0; j < len; j++) {
                Entry e = tab[j];
                if (e != null && e.get() == null)
                    expungeStaleEntry(j);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值