🟡 ThreadLocal

吞佛童子2022年6月20日
  • Java
  • concurrency
大约 14 分钟

🟡 ThreadLocal

1. 类注释

  • ThreadLocal 类提供线程局部变量,
  • 这种变量在多线程环境下访问(get,set)时能保证各个线程的变量独立于其他线程内的变量,
  • ThreadLocal 实例通常来说都是 private static 类型,用于关联线程的上下文。
  • ThreadLocal 实例在线程生命周期内起作用,当线程消亡后,ThreadLocal 实例 将被 GC 回收

[注:] 为什么通常来说 ThreadLocalstatic?

  • static 修饰,表示为类静态变量,属于这个类,而不属于某个类实例
  • 在类初始化时被加载,分配内存,且只初始化一次
  • 所有的类实例均可以使用该对象
  1. 适用环境
  • 多线程并发下对同一个变量进行不同操作
  1. 作用
  • 实现变量在不同线程下的隔离,每个线程都有自己关于该变量的副本
  1. 优点
  • 保证了多线程下的数据安全,避免加锁的性能损失,以空间换时间

2. 使用

public class UserThreadLocal {
    static ThreadLocal<String> str = new ThreadLocal<>();
    public String getStr() {return str.get();}
    public void setStr(String j) {str.set(j);}
    public static void main(String[] args) {
        UserThreadLocal userThreadLocal = new UserThreadLocal();
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    userThreadLocal.setStr(Thread.currentThread().getName() + "的数据");
                    System.out.println(Thread.currentThread().getName() + " 编号 " + userThreadLocal.getStr());
                }
            });
            thread.setName("线程" + i);
            thread.start();
        }
    }
}

3. 属性

    /**
     * 每个线程的 每个 TL 都有一个对应的 hashCode,取决于上一个 TL 变量的 hashCode & 增长量
     * 该方法尽可能保证 hash 分布的均匀
     */
    private final int threadLocalHashCode = nextHashCode();

    /**
     * 遵循原子更新,起始值 = 0
     */
    private static AtomicInteger nextHashCode = new AtomicInteger();

    /**
     * 该线程每增加一个 TL 变量,该 TL 变量的 hash 增加 0x61c88647
     * 这个值为 黄金分割数,可以让产生的 hash 分布均匀
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * 获取下一个 TL 变量应该对应的 hash code
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

4. 构造函数

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

5. 常见方法

1) get()

    /**
     * 返回当前线程存储的某个 TL [ThreadLocal] 变量的值
     * 若当前线程下该 TL 变量没有 value 值,
     * 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(); // 获取当前线程
        ThreadLocalMap map = getMap(t); // 获取当前线程的 ThreadLocalMap
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this); // 获取 ThreadLocalMap 中 key = 该 TL 的 Entry (内含 value)
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value; // 非空,返回 value
                return result;
            }
        }
        // map == null 初始化 map
        return setInitialValue();
    }

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        // Thread 类有很多属性,例如 线程 id、优先级等,还有一个属性就是 threadLocals,该属性所属的类就是 ThreadLocalMap
        return t.threadLocals; 
    }
    
    /**
     * 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(); // null
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value); // 在 map 中设置当前 TL 变量的值为 null
        else
            createMap(t, value);
        return value;
    }
    
    /**
     * 返回当前线程该 TL 变量的初始值 null
     * 当之前没有设置 该 TL 变量的值,却通过 GET 方法调用时,会触发该方法
     *
     * 如果不想返回null,可以 Override 进行覆盖
     *
     * @return the initial value for this thread-local
     */
    protected T initialValue() {
        return null;
    }
    
    /**
     * 为当前线程创建 ThreadLocalMap,且添加 key = 该TL 变量,val = 给定值的 K-V 对
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

2) set(T value)

    /**
     * 给当前线程的 该TL 变量设置值
     *
     * @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); // 获取当前线程的 ThreadLocalMap
        if (map != null)
            map.set(this, value); // 已经存在 map,设置 该TL变量值为 value
        else
            createMap(t, value); // 不存在 map,创建一个 map,并添加 K-V 对
    }

3) remove()

    /**
     * 删除当前线程的该 TL 变量
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread()); // 获取当前线程的 ThreadLocalMap
         if (m != null)
             m.remove(this); // 删除 map 中的该 TL 变量
     }

6. 内部类

1) ThreadLocalMap 构造函数 & 属性

    /**
     * ThreadLocalMap 是一个为了存储线程本地变量而特别设计的 hash map 结构
     * 该类不对 ThreadLocal 类以外的任何类提供外部访问方法
     * key 使用的是弱引用
     */
    static class ThreadLocalMap {

        /**
         * 初始容量大小,必须为 2 的幂
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * 存放节点类的数组,必须为 2 的幂,可能会进行扩容操作
         */
        private Entry[] table;

        /**
         * 节点个数
         */
        private int size = 0;

        /**
         * 容量阈值,超过就会扩容
         */
        private int threshold; // 初始 == 0

        /**
         * 容量阈值至少为 len 的 2/3
         */
        private void setThreshold(int len) {
            threshold = len * 2 / 3;
        }

        /**
         * 返回下一个下标,若超范,返回 0
         */
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

        /**
         * 返回上一个节点下标,若超范,返回 len - 1 即数组最后一个下标,这样可以造成循环
         */
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

        /**
         * 构造函数
         * 将 firstKey - firstValue 键值对存入其中
         * 为懒加载模式,必须等到要放入元素时,才进行创建工作
         */
        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
            table = new Entry[INITIAL_CAPACITY]; // 初始数组长度 == 16
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); // 确定存放数组的下标位置
            table[i] = new Entry(firstKey, firstValue); // 在该下标处放置该节点
            size = 1;
            setThreshold(INITIAL_CAPACITY); // 初始化容量阈值
        }

        /**
         * 构造函数
         * 创建一个 ThreadLocalMap,包含 父map 的所有 TL 变量
         *
         * @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(); // 父的 TL 变量
                    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++;
                    }
                }
            }
        }
}

2) 再内部类

    /**
     * 节点类
     * 保存 K-V 结构,key 为 ThreadLocal 变量,且为弱引用
     * 意味着当 key 不再被引用时,这时 entry 可以从 table 中清除
     */
    static class Entry extends WeakReference<ThreadLocal<?>> {
        /** The value associated with this ThreadLocal. */
        Object value;

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

3) 常用方法

① getEntry(ThreadLocal<?> key)

        /**
         * 获取某个 TL 变量对应的 value 值,只有在准确命中时,直接返回
         * 若该下标处 key 值不为给定 key值,则需要通过下面的函数进行线性遍历
         * 这里说明了对 hash 冲突的处理,采用的不是 HashMap 的拉链法,而是线性探测,每个数组下标处最多存放一个节点
         *
         * @param  key the thread local object
         * @return the entry associated with key, or null if no such
         */
        private Entry getEntry(ThreadLocal<?> key) {
            int i = key.threadLocalHashCode & (table.length - 1); // 每个 TL 变量都会有自己的 hashCode
            Entry e = table[i];
            if (e != null && e.get() == key)
                return e; // 命中直接返回
            else
                return getEntryAfterMiss(key, i, e);
        }

        /**
         * 未命中时的节点查找
         *
         * @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 Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
            Entry[] tab = table;
            int len = tab.length;

            while (e != null) {
                ThreadLocal<?> k = e.get(); // 当前遍历到的节点处的 TL 值
                if (k == key)
                    return e; // 找到,返回
                if (k == null)
                    expungeStaleEntry(i); // 遇到空 TL,进行过期节点的清理 & 重新 rehash
                else
                    i = nextIndex(i, len); // 下标增长,这里是循环查找
                e = tab[i]; // 整个节点都为空,则退出循环
            }
            return null;
        }
        
        /**
         * 过期 key 的探测式清理,过期key ==> key == null的节点
         *
         * @param staleSlot index of slot known to have null key
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         */
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // 删除过期节点
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // 从过期节点向后遍历
            // 若再遇到过期节点,仍是进行删除
            // 若为未过期节点,则判断是否需要 rehash 放在更好的位置
            // 遇到 null 退出循环,返回 null 处下标 
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--; // 过期节点的清理
                } else {
                    int h = k.threadLocalHashCode & (len - 1); // 本应该所处的下标
                    // 非过期节点,不处于应该处在的下标处,则调整其位置
                    if (h != i) {
                        tab[i] = null; // 实际所处的下标

                        // 如果本该处的下标处已经有节点,则线性查找可以插入的空位置
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

② set(ThreadLocal<?> key, Object value)

        /**
         * 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(); // 启发式清理后,容量超过阈值,进行扩容操作
        }
        
        /**
         * 该下标处有过期节点,此时,将新的 K-V 数据覆盖过期节点
         *
         * 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;

            // 此时为从后向前清理过期节点,直到遇到 null
            int slotToExpunge = staleSlot;
            for (int i = prevIndex(staleSlot, len); (e = tab[i]) != null; i = prevIndex(i, len))
                if (e.get() == null)
                    slotToExpunge = i; // 该下标处有过期节点

            // 从前往后遍历,遇到该节点,则覆盖新值,
            for (int i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();

                // 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; // 将该节点和前面过期节点位置进行交换,从而保证 hash 表的有序性

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

                // 整个过程只有这一个过期节点,且其他下标处均非空
                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);
        }
        

        /**
         * 启发式清理
         *
         * @param i 从 i 处往后进行清理操作
         *
         * @param n 扫描数量控制,
         * 第一次为 n 个下标的扫描,正常情况下若未遇到过期节点,则下次继续扫描 n/2 个,再下次 n/4 个,直到 n == 0
         * 若某次遇到了过期节点,则 n == len,进行全部扫描
         *
         * @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
                    n = len;
                    removed = true;
                    i = expungeStaleEntry(i); // 过期节点探测式清理
                }
            } while ( (n >>>= 1) != 0); // 没有遇到,n /2
            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();

            // 容量超过阈值的 0.75
            if (size >= threshold - threshold / 4)
                resize();
        }

        /**
         * 遍历,删除数组中所有过期节点
         */
        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);
            }
        }
    }

        /**
         * 扩容,变为原来的 2 倍
         */
        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; // 协助 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;
        }

③ remove(ThreadLocal<?> key)

        /**
         * 删除某个 TL
         */
        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); // 进行过期节点的删除,在遇到 null 之前判断其他值是否有必要进行 rehash 操作,放入更合适的位置
                    return;
                }
            }
        }

7. InheritableThreadLocal

1) 作用

  • 想要 共享 线程的 ThreadLocal 数据
  • 使用 InheritableThreadLocal 可以实现多个线程访问 ThreadLocal 的值
  • 主线程中创建一个 InheritableThreadLocal 的实例,然后在子线程中得到这个 InheritableThreadLocal 实例设置的值

2) 使用

private void test() {    
final ThreadLocal threadLocal = new InheritableThreadLocal(); // 父线程为 InheritableThreadLocal      
threadLocal.set("六弦之首 苍);    
Thread t = new Thread() { // 子线程可以得到父线程的 TL       
    @Override        
    public void run() {            
      super.run();            
      Log.info( "男神:" + threadLocal.get());        
    }    
  };          
  t.start(); 
} 

3) 源码

/**
 * InheritableThreadLocal 继承 ThreadLocal 类,子线程可以继承父类的 TL 值
 * 当子线程被创建时,子线程将接收到父类所有的可以被继承的 TL 变量
 * 通常情况下,子线程的 TL 变量和父线程的相同
 * 但是可以通过重写 childValue() 方法和父线程的值不同
 *
 * <p>Inheritable thread-local variables are used in preference to
 * ordinary thread-local variables when the per-thread-attribute being
 * maintained in the variable (e.g., User ID, Transaction ID) must be
 * automatically transmitted to any child threads that are created.
 */

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
    /**
     * 若想根据父值得到不同于父值的结果,可以重写该方法
     *
     * @param parentValue the parent thread's value
     * @return the child thread's initial value
     */
    protected T childValue(T parentValue) {
        return parentValue;
    }

    /**
     * Get the map associated with a ThreadLocal.
     *
     * @param t the current thread
     */
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }

    /**
     * Create the map associated with a ThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the table.
     */
    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }
}

8. 弱引用 & 内存泄漏

1) 关系整理

  1. 只要当前线程存在,那么当前线程就会有 ThreadLocalMap threadLocals
    • 当插入任意一个 TL 变量时,对应线程的 ThreadLocalMap 就会被初始化,且放入初始 K-V 数据
  2. ThreadLocalMap 中存放的是 TL - TL value 的 K-V 对
    • 当某个 TL 不再被使用时,从 TL的栈引用 -> 堆中该 TL 的引用关系就不存在了,只剩下上面那条引用链关系
    • 此时,我们希望 ThreadLocalMap 中该 TL - TL value K-V 对能够及时删除,从而避免内存泄露问题

2) 内存泄露

  1. 发生的前提[2 个前提需同时存在]

    • CurrentThread 仍存在,导致 CurrentThread 对象 -> ThreadLocalMap 对象 引用关系仍存在
    • 没有使用 TL.remove() 方法删除掉,导致 ThreadLocalMap 对象 -> TL - TL value 引用关系仍存在
  2. 如何打破

    • 线程结束自动回收,但若是使用线程池,线程一直不被回收,则不好处理
    • TL 变量用完后,及时通过 TL.remove() 方法回收

3) 强引用 VS 弱引用

  1. 背景

    • 若使用的是线程池,当前线程一直存在
    • 且 TL 变量使用后,没有通过 TL.remove() 回收
  2. 若是强引用

    • ThreadLocalMap 对象 -> TL - TL value 引用关系存在
    • 由于 TL - TL value -> 某个 TL 对象强引用
    • 该 TL 对象永远不会被 GC 回收,
    • ThreadLocalMap 如果想要在增删 TL 的时候进行过期 TL 的清理,
    • 由于所有的无论实际 TL 是不是过期的,key 均非空,即使想做优化清理也无法判断哪些是有效TL,哪些是可以被清理的TL
  3. 若是弱引用

    • ThreadLocalMap 对象 -> TL - TL value 引用关系一直存在
    • 由于 TL - TL value -> 某个 TL 对象弱引用
    • 只要进行 GC,由于该 TL 对象已经不存在 TL 的引用 -> 某个 TL 对象 的引用关系,只存在 TL - TL value -> 某个 TL 对象 的弱引用,
    • 所以 该 TL 对象就会被 GC 回收,对应的 ThreadLocalMap 中该 key == null
    • ThreadLocalMap 如果想要在增删 TL 的时候进行过期 TL 的清理,
    • 只需要判断 key 是否 == null 即可区分是否为过期节点,从而进行过期节点的优化删除,比如说将对应的 value 删除,重新 hash 等,减缓没有手动 TL.remove() 下的内存泄漏情况
上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou