Java ThreadLocal源码总结 ThreadLocal源码注释翻译和解析中英文对照版

版本
JDK8(JDK1.8)

ThreadLocal类源码重点
1.ThreadLocal类是用于创建线程私有变量的类,其原理是,在每个Thread类中都有一个ThreadLocalMap类,就是一个Hash表,而这个ThreadLocalMap以ThreadLocal为键,以线程私有变量为值,又由于每个Thread对象的ThreadLocalMap都不同,所以虽然只有同一个ThreadLocal对象,也可以在不同的线程中对应不同的值

2.从ThreadLocal的get方法就可以知道,为什么不同线程调用同一个ThreadLocal对象的get方法返回的值可以不一样,
因为get()方法一直获取的是当前线程中的ThreadLocalMap,不同线程的ThreadLocalMap是不一样的

public T get() {
        // 获得当前运行线程
        Thread t = Thread.currentThread();
        // 取出当前线程内部的 ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        // 如果线程内部的 ThreadLocalMap不为空
        if (map != null) {
            // 以当前ThreadLocal对象为为键,取出<ThreadLocal, Object>键值对
            ThreadLocalMap.Entry e = map.getEntry(this);
            // 如果键值对不为空
            if (e != null) {
                @SuppressWarnings("unchecked")
                // 取出键值对中的值
                T result = (T)e.value;
                return result;
            }
        }
       // 如果线程内部的 ThreadLocalMap为空,调用设置并获取初始值的方法
        return setInitialValue();
    }

注: 从上面可以看出ThreadLocalMap是惰性创建的,只有在使用ThreadLocal的get()、set()这些方法时才会尝试创建ThreadLocalMap,初始化代码如下

 private T setInitialValue() {
        // 获取初始值
        T value = initialValue();
        // 获取当前线程
        Thread t = Thread.currentThread();
        // 取出当前线程中的ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        // 如果ThreadLocalMap不为空,则以当前ThreadLocal对象为键,初始值为值
        // 将该键值对添加进ThreadLocalMap
        if (map != null) {
            map.set(this, value);
        } 
        // 如果ThreadLocalMap为空
        else {
            // 创建 ThreadLocalMap对象
            createMap(t, value);
        }
        // 如果该ThreadLocal对象原先属于TerminatingThreadLocal类或其子类
        if (this instanceof TerminatingThreadLocal) {
            // 则将其添加到Collection<TerminatingThreadLocal<?>> 中
            // 用于线程结束时释放TerminatingThreadLocal<?>中的?资源
            TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
        }
        // 返回初始值
        return value;
    }

3.ThreadLocal内存泄漏问题,因为ThreadLocalMap是由一个Entry数组实现的,Entry就是一个键值对类,如下,

static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal.
             * 与此ThreadLocal关联的值。
             */
            Object value;

            // 内存泄漏,ThreadLocal被GC回收了为null,则无法通过null取出value,
            // 可以通过expungeStaleEntry回收键为null的Entry
            Entry(ThreadLocal<?> k, Object v) {
                // 键是弱引用,逃不过一次GC收集,软引用直到空间不足才回收
                // 为什么设为弱引用,因为ThreadLocal一开始都会有强引用,
                // 如果不想要了,设为null,则想GC收集它,如果不设为弱引用,则一直无法回收
                super(k);
                // 值是强引用,因为不清楚这个值会不会还有其他强引用,
                // 如果没有,若设置为弱引用,则取出的值可能是null
                value = v;
            }
        }

内存泄漏原因: 可以看出Entry的键ThreadLocal是弱引用类型,弱引用是无法逃过一次GC的,所以当外部的ThreadLocal的强引用释放,即一开始创建ThreadLocal时的变量置为null时,Entry里面的键ThreadLocal也会被GC,而键被垃圾收集了后,就无法通过键找到对应的value,就无法使用该value了,又因为该value是强引用类型,所以无法直接被垃圾收集,就造成了内存泄漏

内存泄漏条件: 当然这种内存泄漏只有在线程池中才会体现,因为一般Thread对象运行完后会销毁,而ThreadLocalMap也随之销毁,则Entry也销毁,但是在线程组中Thread会被重复利用,则ThreadLocalMap也会被重复利用

为什么value不设为弱引用:因为不确定value的对象是否还有其他外部强引用,如果设为弱引用,则使用get方法取出的value可能是null

为什么key设为弱引用:因为一开始一定会创建一个ThreadLocal key = new ThreadLocal(),这就是强引用,所以当我们让 key = null时,肯定想让该ThreadLocal对象被内存回收,如果设为强引用,则无法回收

内存泄漏解决办法:ThreadLocalMap类在增删改查方法中都会调用**expungeStaleEntry()**方法去回收key为nul的Entry,将回收操作分摊在每一次增删改查操作中

4.ThreadLocal类有一个子类InheritableThreadLocal,用于实现可继承的ThreadLocal,但其实InheritableThreadLocal类只重写了ThreadLocal类三个方法childValue()、getMap、createMap()

InheritableThreadLocal源码具体可以看我的这篇文章 InheritableThreadLocal

5.ThreadLocal类中的ThreadLocalMap是实现ThreadLocal功能的数据结构,了解其增删改查方法很有必要

ThreadLocalMap源码具体可以看我的这篇文章 ThreadLocalMap

ThreadLocal类源码

package java.lang;
import jdk.internal.misc.TerminatingThreadLocal;

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).
 * 此类提供线程局部变量。
 * 这些变量不同于它们的普通对应变量,
 * 因为访问它们的每个线程(通过其get或set方法)都有自己的、独立初始化的变量副本。
 * ThreadLocal实例通常是希望将状态与线程(例如,用户ID或事务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.
 * 
 * 例如,下面的类生成每个线程本地的唯一标识符。
 * 线程的id在第一次调用ThreadId.get()时被分配,并且在后续调用中保持不变。
 * 
 * 
 * <pre>
 * import java.util.concurrent.atomic.AtomicInteger;
 *
 * public class ThreadId {
 *     // Atomic integer containing the next thread ID to be assigned
 *     // 包含要分配的下一个线程ID的原子整数
 *     private static final AtomicInteger nextId = new AtomicInteger(0);
 *
 *     // Thread local variable containing each thread's ID
 *     // 包含每个线程ID的线程局部变量
 *     private static final ThreadLocal<Integer> threadId =
 *         new ThreadLocal<Integer>() {
 *             @Override
 *             protected Integer initialValue() {
 *                 return nextId.getAndIncrement();
 *             }
 *     };
 *
 *     // Returns the current thread's unique ID, assigning it if necessary
 *     // 返回当前线程的唯一ID,必要时分配它
 *     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).
 * 只要线程处于活动状态且ThreadLocal实例可访问,
 * 每个线程都持有对其线程局部变量副本的隐式引用;
 * 线程消失后,其线程本地实例的所有副本都将接受垃圾收集(除非存在对这些副本的其他引用)。
 *
 * @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.
     * ThreadLocals依赖于附加到每个线程的每线程线性探测哈希映射
     * (thread.ThreadLocals和inheritableThreadLocals)。
     * ThreadLocal对象充当键,通过threadLocalHashCode进行搜索。
     * 这是一个自定义哈希代码(仅在ThreadLocalMaps中有用),
     * 在相同线程使用连续构造的ThreadLocal的常见情况下消除冲突,而在不太常见的情况下保持良好的性能。
     * 
     * // 获取nextHashCode并将nextHashCode的值增加HASH_INCREMENT
     * // nextHashCode初始值为0,增量为 0x61c88647
     * 
     */
    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.
     * 连续生成的散列码之间的差异——将隐式顺序线程本地ID转换为近似最优分布的乘法散列值,
     * 以获得两个大小表的幂。
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * Returns the next hash code. 返回下一个哈希代码。
     */
    private static int nextHashCode() {
        // 获取nextHashCode并将nextHashCode的值增加HASH_INCREMENT
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

    /**
     * Returns the current thread's "initial value" for this
     * thread-local variable.  This method will be invoked the first
     * 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.  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}.
     * 返回此线程局部变量的当前线程“初始值”。
     * 当线程第一次使用get方法访问变量时,将调用此方法,
     * 除非线程先前调用了set方法,在这种情况下,不会为线程调用initialValue方法。
     * 通常,每个线程最多调用一次此方法,
     * 但在随后调用remove和get时,可以再次调用此方法。
     * 
     * 
     *
     * <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.
     * 这个实现只返回null;
     * 如果程序员希望线程局部变量具有除null以外的初始值,
     * 则必须对ThreadLocal进行子类化,并重写此方法。通常,将使用匿名内部类。
     *
     * @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}.
     * 创建线程局部变量。变量的初始值是通过调用Supplier上的get方法确定的。
     *
     * @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.
     * 返回此线程局部变量的当前线程副本中的值。
     * 如果变量对于当前线程没有值,则首先将其初始化为调用initialValue方法返回的值。
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        // 获得当前运行线程
        Thread t = Thread.currentThread();
        // 取出当前线程内部的 ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        // 如果线程内部的 ThreadLocalMap不为空
        if (map != null) {
            // 以当前ThreadLocal对象为为键,取出<ThreadLocal, Object>键值对
            ThreadLocalMap.Entry e = map.getEntry(this);
            // 如果键值对不为空
            if (e != null) {
                @SuppressWarnings("unchecked")
                // 取出键值对中的值
                T result = (T)e.value;
                return result;
            }
        }
       // 如果线程内部的 ThreadLocalMap为空,调用设置并获取初始值的方法
        return setInitialValue();
    }

    /**
     * Returns {@code true} if there is a value in the current thread's copy of
     * this thread-local variable, even if that values is {@code null}.
     * 如果此线程局部变量的当前线程副本中存在值,则返回true,即使该值为null
     *
     * @return {@code true} if current thread has associated value in this
     *         thread-local variable; {@code false} if not
     *         返回true,如果当前线程在此线程局部变量中有关联的值;如果不是返回false
     * 
     */
    boolean isPresent() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        return map != null && map.getEntry(this) != null;
    }

    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     * set()的变量以建立初始值。在用户重写set()方法的情况下代替set()使用。
     *
     * @return the initial value
     */
    private T setInitialValue() {
        // 获取初始值
        T value = initialValue();
        // 获取当前线程
        Thread t = Thread.currentThread();
        // 取出当前线程中的ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        // 如果ThreadLocalMap不为空,则以当前ThreadLocal对象为键,初始值为值
        // 将该键值对添加进ThreadLocalMap
        if (map != null) {
            map.set(this, value);
        } 
        // 如果ThreadLocalMap为空
        else {
            // 创建 ThreadLocalMap对象
            createMap(t, value);
        }
        // 如果该ThreadLocal对象原先属于TerminatingThreadLocal类或其子类
        if (this instanceof TerminatingThreadLocal) {
            // 则将其添加到Collection<TerminatingThreadLocal<?>> 中
            // 用于线程结束时释放TerminatingThreadLocal<?>中的?资源
            TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
        }
        // 返回初始值
        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.
     * 将此线程局部变量的当前线程副本设置为指定值。
     * 大多数子类不需要重写此方法,只依赖initialValue方法来设置线程局部变量的值。
     *
     * @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();
        ThreadLocalMap 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.
     * 
     * 删除此线程局部变量的当前线程值。
     * 如果此线程局部变量随后被当前线程get()读取,则其值将通过调用其initialValue方法重新初始化,
     * 除非当前线程在此期间将其值设置为set。
     * 这可能会导致在当前线程中多次调用initialValue方法。
     *
     * @since 1.5
     */
     public void remove() {
         // 获取当前线程的threadLocals属性即t.threadLocals
         // 如果是InheritableThreadLocal则会重写getMap(.)方法返回t.inheritableThreadLocals
         // 即当前线程的inheritableThreadLocals属性
         ThreadLocalMap m = getMap(Thread.currentThread());

         // 如果线程中的ThreadLocalMap不为空
         if (m != null) {
             // 则移除以当前ThreadLocal为键的键值对,
             // 即从Entry数组移除对应的Entry对象
             // 此时已经是ThreadLocalMap内部类调用其内部定义的方法
             // 而不是ThreadLocal调用方法了
             m.remove(this);
         }
     }

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     * 获取与ThreadLocal关联的映射。在InheritableThreadLocal中重写。
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    /**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     * 创建与ThreadLocal关联的映射。在InheritableThreadLocal中重写。
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map 映射的初始条目的值
     */
    void createMap(Thread t, T firstValue) {
        // 设置Thread的threadLocals属性,创建一个ThreadLocalMap赋值给它
        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.
     * 方法childValue在子类InheritableThreadLocal中可见地定义,
     * 但在此处内部定义是为了提供CreateInheritatedMap工厂方法,
     * 而无需在InheritableThreadLocal中对映射类进行子类化。
     * 这种技术比在方法中嵌入测试实例更可取。
     */
    T childValue(T parentValue) {
        throw new UnsupportedOperationException();
    }

    /**
     * An extension of ThreadLocal that obtains its initial value from
     * the specified {@code Supplier}.
     * ThreadLocal的扩展,从指定的Supplier获取其初始值。
     */
    static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {

        private final Supplier<? extends T> supplier;

        SuppliedThreadLocal(Supplier<? extends T> supplier) {
            // supplier为null抛出异常
            this.supplier = Objects.requireNonNull(supplier);
        }

        // 重写父类的initialValue()方法,
        // 初始值从supplier.get()方法获得
        @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.
     * ThreadLocalMap是一个定制的哈希映射,仅适用于维护线程本地值。
     * 在ThreadLocal类之外不导出任何操作。该类是包私有的,允许在类线程中声明字段。
     * 为了帮助处理非常大和长期的用法,哈希表条目使用WeakReferences作为键。
     * 但是,由于不使用引用队列,因此只有当表开始耗尽空间时,才能保证删除过时的条目。
     */
    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.
         * 此哈希映射中的条目扩展WeakReference,
         * 使用其主ref字段作为键(始终是ThreadLocal对象)。
         * 请注意,null键(即entry.get() ==null)意味着不再引用该键,
         * 因此可以从表中删除该项。这些条目在下面的代码中称为“过时条目”。
         * 
         * 
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal.
             * 与此ThreadLocal关联的值。
             */
            Object value;

            // 内存泄漏,ThreadLocal被GC回收了为null,则无法通过null取出value,
            // 可以通过expungeStaleEntry回收键为null的Entry
            Entry(ThreadLocal<?> k, Object v) {
                // 键是弱引用,逃不过一次GC收集,软引用直到空间不足才回收
                // 为什么设为弱引用,因为ThreadLocal一开始都会有强引用,
                // 如果不想要了,设为null,则想GC收集它,如果不设为弱引用,则一直无法回收
                super(k);
                // 值是强引用,因为不清楚这个值会不会还有其他强引用,
                // 如果没有,若设置为弱引用,则取出的值可能是null
                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的幂。
         */
        private 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.
         * 设置调整大小阈值以保持最差的2/3负载系数。
         */
        private void setThreshold(int len) {
            // 下一次容量为给定容量的2/3
            threshold = len * 2 / 3;
        }

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

        /**
         * Decrement i modulo len.
         * 减量i对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).
         * ThreadLocalMaps are constructed lazily, so we only create
         * one when we have at least one entry to put in it.
         * 构建一个最初包含(firstKey, firstValue)的新映射。
         * ThreadLocalMaps是惰性构造的,所以我们只有在至少有一个条目要放入时才创建一个。
         * 
         * 
         */
        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            // ThreadLocalMap底层是Entry数组
            // 初始创建数组长度为16
            table = new Entry[INITIAL_CAPACITY];
            // threadLocalHashCode初始为0,往后会有一个增量 HASH_INCREMENT = 0x61c88647
            // 根据HashCode计算在数组的索引
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            // 创建一个Entry键值对
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            // 设置下次要扩容的容量
            // 即达到该值时,会发生扩容
            setThreshold(INITIAL_CAPACITY);
        }

        /**
         * Construct a new map including all Inheritable ThreadLocals
         * from given parent map. Called only by createInheritedMap.
         * 构造一个新映射,其中包含来自给定父映射的所有可继承ThreadLocals。
         * 仅由createInheritedMap调用。
         *
         * @param parentMap the map associated with parent thread. 与父线程关联的映射。
         */
        private ThreadLocalMap(ThreadLocalMap parentMap) {
            // 获取给定ThreadLocalMap 的 Entry数组
            Entry[] parentTable = parentMap.table;
            // 获取Entry[]数组长度,不代表键值对数量
            int len = parentTable.length;
            // 设置阈值,达到阈值后会扩容
            setThreshold(len);
            // 根据Entry数组长度创建一个新的Entry数组
            table = new Entry[len];

            //遍历给定的父ThreadLocal的Entry数组
            for (Entry e : parentTable) {
                // 如果键值对不为空
                if (e != null) {
                    @SuppressWarnings("unchecked")
                    //获取Entry中的键
                    ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                    // 如果key不为null
                    if (key != null) {
                        // 将父ThreadLocalMap中的Entry中的值传入该方法
                        // 返回经过对应处理的子ThreadLocalMap的Entry中的值
                        Object value = key.childValue(e.value);
                        // 重新创建一个子ThreadLocalMap的Entry,
                        // 键仍然是父ThreadLocalMap的键,值是上面获取的值
                        Entry c = new Entry(key, value);
                        // 计算该Entry在新的Entry数组中的索引,
                        // 根据键的threadLocalHashCode计算
                        int h = key.threadLocalHashCode & (len - 1);
                        while (table[h] != null)
                            // 开放寻址法找到下一个为null的索引,才能放入Entry
                            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.
         * 获取与key关联的条目。此方法本身只处理快速路径:
         * 直接命中现有key。否则它将中继到getEntryAfterMiss。
         * 这是为了最大限度地提高直接命中的性能,部分原因是使此方法易于内联。
         *
         * @param  key the thread local object
         * @return the entry associated with key, or null if no such
         */
        private Entry getEntry(ThreadLocal<?> key) {
            // 计算key对应的索引
            int i = key.threadLocalHashCode & (table.length - 1);
            // 根据计算出的索引从table数组中获取Entry
            Entry e = table[i];
            // 如果Entry不为空 且Entry的键为给定的key
            if (e != null && e.get() == key)
                // 返回entry
                return e;
            else
                // 如果e为null,返回null,如果e不为空,从索引i处开始找键等于key的Entry
                // 在查找过程中如果发现Entry不为空,但key为空,则释放该Entry
                // 查找直到Entry为null 则说明找不到返回 null
                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] table[i]中的条目
         * @return the entry associated with key, or null if no such 
         *         与key关联的条目,如果没有,则为null
         */
        private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
            Entry[] tab = table;
            int len = tab.length;

            while (e != null) {
                // 获取entry的key
                ThreadLocal<?> k = e.get();
                // 如果获取的key等于给定key
                if (k == key)
                    return e;
                // 如果k为null
                if (k == null)
                    // 消除该Entry
                    expungeStaleEntry(i);
                else
                    // i自增取模
                    i = nextIndex(i, len);
                // 前面消除i处的Entry后,还会重新计算i后面的Entry因为处于的位置
                // 将其移到合适的位置,所以这里e = tab[i] 不一定是 e = null
                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(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.
            // 我们不像get()那样使用快速路径,因为使用set()创建新条目至少和替换现有条目一样常见,
            // 在这种情况下,快速路径失败的频率更高。

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            // 从键对应索引开始找
            for (Entry e = tab[i];
                // 遇到Entry为null停下来
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();
                // 在这里执行的代码都是Entry不为null

                // 如果直到对应entry,将其值设为新值
                if (k == key) {
                    e.value = value;
                    return;
                }

                // 如果遇到key为null
                if (k == null) {
                    // 从i往后找一个key等于k的Entry,与该过时条目交换
                    // 或者找不到则将该过时条目替换成新创建的Entry(key, value)
                    // 同时附带一些释放过时条目的操作
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            // 经过上面操作,找不到key为k的Entry,即原本不存在该Entry
            // 则创建一个新的Entry,放置在i索引处
            // 此时i不是最开始的i,而是经过上面循环后,Entry[]中为null处的一个索引
            // 所以可以直接赋值,不用担心覆盖
            tab[i] = new Entry(key, value);
            int sz = ++size;
            // 如果没有找到可以释放的Entry,且目前的size大于阈值
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                // 则删除表中所有过时的条目,再双倍扩容,
                // 复制仍然没过时的Entry到新数组中
                rehash();
        }

        /**
         * Remove the entry for key.
         * 删除键对应的条目。
         */
        private void remove(ThreadLocal<?> key) {
            // table是ThreadLocalMap内部类定义的Entry[]
            Entry[] tab = table;
            // 获取Entry数组的长度
            int len = tab.length;
            // 根据ThreadLocal的threadLocalHashCode属性算出索引
            // 即ThreadLocal对应的Entry在数组中的位置
            int i = key.threadLocalHashCode & (len-1);
            for (Entry e = tab[i];
                 e != null;
                 // 如果索引冲突了,采用开发寻址法解决
                 // 即往后走直到找到Entry中的键等于key
                 e = tab[i = nextIndex(i, len)]) {
                // 如果找到了对应的Entry
                if (e.get() == key) {
                    // e是Reference的子类,调用的是其父类的clear()方法
                    // 内部实现为:
                    // this.referent = null;
                    // 这个referent就是Entry中的key,将其置空
                    e.clear();
                    // 消除旧的Entry,防止内存泄漏,因为上一步将key置为空了
                    // 则无法通过key访问到value,而value又是强引用,会无法GC
                    //此时i可能不是最开始的i,而是对应Entry的索引
                    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.
         * 用指定key的条目替换set操作期间遇到的过时条目。
         * 值参数中传递的值存储在条目中,无论指定键的条目是否已存在。
         *
         * 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.)
         * 作为一个副作用,此方法将删除包含过时项的“run”中的所有过时项。
         * (运行是两个空插槽之间的一系列条目。)
         *
         * @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;
            // i是staleSlot自减取模的值
            for (int i = prevIndex(staleSlot, len);
                // 当Entry不为空
                 (e = tab[i]) != null;
                 // 一直往前面找
                 i = prevIndex(i, len))
                 // 如果Entry的键为null
                if (e.get() == null)
                     // 则将需要收集的下标往前移动
                    slotToExpunge = i;

            // Find either the key or trailing null slot of run, whichever
            // occurs first
            // 查找run的键或尾部空槽,以先发生的为准
            // 从过时entry后面开始找
            for (int i = nextIndex(staleSlot, len);
                // 如果entry不为空
                 (e = tab[i]) != null;
                 // i自增取模
                 i = nextIndex(i, len)) {
                // 获取entry的键
                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.
                // 若我们找到了键,那个么我们需要将它和陈旧的条目交换,
                // 以保持哈希表的顺序。
                // 然后,可以将新过时的插槽或其上方遇到的任何其他过时插槽发送到expungeStaleEntry,
                // 以删除或重新刷新运行中的所有其他条目。

                // 如果找到了key对应的Entry
                if (k == key) {
                    // 将值替换成新值
                    e.value = value;

                    // 将找到的entry和过时条目互换
                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists
                    // 在前一个过时条目(如果存在)处开始删除
                    if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
                    // expungeStaleEntry(slotToExpunge) 从slotToExpunge扫描key为null的entry
                    // 将其释放,并将每个key不为空的entry重新寻找安放位置
                    // 返回一个索引是entry为null的数组索引
                    // len是entry数组的长度
                    // cleanSomeSlots 是从给定expungeStaleEntry(slotToExpunge)返回值处
                    // 往后找log2(len)次,找到一个则重新再找log2(len)
                    // 直到找了log2(len)次,找不到Entry不为空但key为空的Entry为止
                    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
            // 如果找不到key,请将新条目放入过时的插槽中
            // 释放原来的entry的value
            tab[staleSlot].value = null;
            // 在过时条目处放入新Entry
            tab[staleSlot] = new Entry(key, value);

            // If there are any other stale entries in run, expunge them
            // 如果运行中有任何其他过时条目,请将其删除
            if (slotToExpunge != staleSlot)
                // expungeStaleEntry(slotToExpunge) 从slotToExpunge扫描key为null的entry
                // 将其释放,并将每个key不为空的entry重新寻找安放位置
                // 返回一个索引是entry为null的数组索引
                // len是entry数组的长度
                // cleanSomeSlots 是从给定expungeStaleEntry(slotToExpunge)返回值处
                // 往后找log2(len)次,找到一个则重新再找log2(len)
                // 直到找了log2(len)次,找不到Entry不为空但key为空的Entry为止
                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
         * 通过重新灰化位于staleSlot和下一个空插槽之间的任何可能冲突的条目来删除过时条目。
         * 这还将删除在尾部null之前遇到的任何其他过时条目。
         *
         * @param staleSlot index of slot known to have null key 已知具有空key的插槽索引
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         * staleSlot之后的下一个空插槽的索引(staleSlot和此插槽之间的所有内容都将被检查以进行删除)
         * 
         */
        private int expungeStaleEntry(int staleSlot) {
            // ThreadLocalMap中的Entry数组
            Entry[] tab = table;
            // 获取Entry数组长度
            int len = tab.length;

            // expunge entry at staleSlot
            // 消除 staleSlot索引处的entry
            // 将Entry的值置为null
            tab[staleSlot].value = null;
            // 将Entry对应索引处引用置为空
            // 即将指向Entry对象的引用去掉,让Entry对象回收
            tab[staleSlot] = null;
            // 键值对数减少1
            size--;

            // Rehash until we encounter null
            // 重新Hash,并清除key为null的Entry,直到遇到Entry为null
            // 重新Hash是因为有些键原来因为Hash冲突,使用开放寻址法解决(即在目标索引后面找空位置放置Entry)
            // 如果清除了Entry本来应该放置的空间,则将Entry移回到它本来应该放置的空间
            Entry e;
            int i;
            // 从staleSlot索引的下一个索引开始,由于nextIndex在超出模值会取模即循环
            // 所以可能从后面清除到前面
            for (i = nextIndex(staleSlot, len);
                // 取出Entry数组中新索引i位置处的Entry
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                // 取出该Entry对应的键
                ThreadLocal<?> k = e.get();
                // 如果键为空
                if (k == null) {
                    // 清除其值的引用,帮助值GC
                    e.value = null;
                    // 清除Entry的引用,帮助键GC
                    tab[i] = null;
                    // 键值对数减一
                    size--;
                } else {
                    // 重新计算该Entry本来应该放置的位置
                    int h = k.threadLocalHashCode & (len - 1);
                    // 如果本来应该放置的位置和现在位置不同
                    if (h != i) {
                        // 将现在位置指向Entry的引用清空
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        // 与Knuth 6.4算法R不同,我们必须扫描到null,因为多个条目可能已经过时
                        // 从本来应该放置的位置开始找为null的位置
                        while (tab[h] != null)
                            // 不为null,则索引加1取模
                            h = nextIndex(h, len);
                        // 将找到的索引h位置引用指向entry
                        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.
         * 试探性地扫描一些单元格以查找过时的条目。
         * 当添加新元素或删除另一个过时元素时,将调用此函数。
         * 它执行对数数量的扫描,作为无扫描(快速但保留垃圾)和与元素数量成比例的扫描数量之间的平衡,
         * 这将查找所有垃圾,但会导致一些插入花费O(n)时间。
         * 
         * 
         *
         * @param i a position known NOT to hold a stale entry. The
         * scan starts at the element after i.
         * 一种已知的不持有过期条目的位置。扫描从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.)
         * 扫描控制:log2(n)单元格被扫描,除非找到过时的条目,在这种情况下,
         * log2(table.length)-1额外的单元格被扫描。
         * 从插入调用时,此参数是元素数,但从replaceStaleEntry调用时,此参数是表长度。
         * (注意:所有这些都可以通过加权n而不是仅仅使用直对数n来改变为或多或少的攻击性。
         * 但是这个版本简单、快速,并且似乎工作得很好。)
         *
         * @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自增取模
                i = nextIndex(i, len);
                // 获取对应的Entry
                Entry e = tab[i];
                // 如果Entry不为null且其key为null
                if (e != null && e.get() == null) {
                    // 找到一个,则重新将n设为长度,即重置查找次数
                    n = len;
                    // 成功修改一个,则返回true
                    removed = true;
                    // 从i处开始往后找,进行释放和重新Hash的操作
                    i = expungeStaleEntry(i);
                }
            // 控制查找次数为log2(n),n>>>=1为n = n >>> 1,>>>是无符号右移
            } 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.
         * 重新包装和/或调整table的尺寸。
         * 首先扫描整个表,删除过时的条目。如果这不能充分缩小表的大小,请将表的大小增加一倍。
         */
        private void rehash() {
            // 删除表中所有过时的条目。
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            // 使用较低的阈值加倍以避免滞后
            // 当元素个数大于3/4 threshold 阈值时
            if (size >= threshold - threshold / 4)
                // 进行扩容,2倍扩容
                // 并遍历数组,将Entry不为空且key不为空的Entry移入新数组
                resize();
        }

        /**
         * Double the capacity of the table.
         * 把table的容量增加一倍。
         */
        private void resize() {
            Entry[] oldTab = table;
            int oldLen = oldTab.length;
            int newLen = oldLen * 2;
            // 创建两倍容量的新Entry数组
            Entry[] newTab = new Entry[newLen];
            int count = 0;

            // 遍历老数组
            for (Entry e : oldTab) {
                // 如果Entry不为空
                if (e != null) {
                    // 获取Entry中的键
                    ThreadLocal<?> k = e.get();
                    // 如果key为空,将其value设为空
                    if (k == null) {
                        e.value = null; // Help the GC 帮助GC
                    } 
                     // 如果k不为空
                    else {
                        // 重新计算该Entry在新Entry数组的索引
                        int h = k.threadLocalHashCode & (newLen - 1);
                        // 当索引冲突时
                        while (newTab[h] != null)
                            //采用开放寻址法,一直往后找空位
                            h = nextIndex(h, newLen);
                        // 找到存放索引,将Entry放入新Entry数组
                        newTab[h] = e;
                        // 新Entry数组里元素个数加1
                        count++;
                    }
                }
            }

            // 设置新的阈值,为给定容量的2/3
            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)
                    //进行释放操作和重新Hash
                    expungeStaleEntry(j);
            }
        }
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lolxxs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值