ThreadLocal详解

一、什么是ThreadLocal

  • ThreadLocal是Java中的一个线程局部变量工具类,它提供了线程级别的变量存储访问操作,每个线程都有自己独立的ThreadLocal实例。

  • 一个ThreadLocal对应线程一个局部变量,一个线程可以有多个ThreadLocal,对应多个变量

二、ThreadLocal解决什么问题

  • 多线程并发场景可以使用ThreadLocal创建线程独有变量,保证线程数据隔离
  • 实现线程范围内的数据共享,可不通过方法参数传递。解决深层次调用的参数传递问题

三、ThreadLocal源码分析

ThreadLocal的实现原理涉及到三个关键的类:ThreadLocal、Thread和ThreadLocalMap。

1. Thread 类(只提取了关键代码解析)

每个线程都有一个Thread对象,其中包含一个ThreadLocalMap对象,用于存储该线程的线程局部变量。在Thread类中,通过ThreadLocal.ThreadLocalMap字段实现对线程局部变量的存取

public
class Thread implements Runnable {
 
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
}

2. ThreadLocal.ThreadLocalMap类(只提取了关键代码解析)

  • ThreadLocalMap是ThreadLocal的内部实现类,是一个自定义的哈希表,用于存储线程局部变量的键值对。
  • ThreadLocalMap的键是ThreadLocal实例,值是线程局部变量的值。每个ThreadLocal实例都对应一个键值对,即线程局部变量的值。
public class ThreadLocal<T> {

    /**
     * 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.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }
		
		
        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;

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

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

内存泄漏问题,为什么Entry类要继承弱引用?

如果 Entry 类不继承 WeakReference<ThreadLocal<?>>,那么在关联的 ThreadLocal对象没有其他强引用时,Entry 对象仍然会被视为可达对象,不会被垃圾回收。这会导致内存泄漏,因为即使 ThreadLocal对象已经没有用处,它和 Entry 对象之间的引用关系仍然存在。

内存泄漏的具体情况如下:

  1. 创建一个 ThreadLocal 对象,并将其做为某个线程的 ThreadLocalMap 中的key。
  2. 当不再需要这个 ThreadLocal 对象时,没有手动清除对它的引用。
  3. 因为 ThreadLocalMap 内部使用的是强引用,所以 ThreadLocal 对象仍然被 ThreadLocalMap 引用(ThreadLocalMap 是通过 ThreadLocal 的静态内部类 ThreadLocalMap 来引用ThreadLocal 的),并间接地引用了对应的 Entry对象(ThreadLocal对象会作为ThreadLocalMap中的Entry对象的key,因此只要ThreadLocal对象的引用存在,对应的Entry对象就无法被垃圾回收)。
  4. 由于 Entry 对象没有被垃圾回收,其中的值(value)也不会被回收释放,占据着内存。
  5. 这种情况下,即使线程结束,ThreadLocalMap 中的 Entry 对象仍然保持对 ThreadLocal 对象的引用(Entry 类中的成员变量持有 ThreadLocal 对象的引用),导致 ThreadLocal 对象无法被垃圾回收。
  6. 在长时间运行的应用中,如果大量 ThreadLocal 对象没有被清理和垃圾回收,就会导致内存泄漏。

因此,通过在 Entry 类中使用 WeakReference<ThreadLocal<?>>,当没有其他强引用时,Entry 对象会被垃圾回收,可以防止内存泄漏

3. ThreadLocal类(只提取了关键代码解析)

  • ThreadLocal是一个泛型类,可通过get()和set()方法对线程局部变量进行存储和读取,实际操作的是线程内部的ThreadLocalMap

  • set()方法:首先获取当前线程,再获取线程下的threadLocals,存在则直接添值,不存在初始化map

public class ThreadLocal<T> {
    /**
     * 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();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * 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.
     *
     * @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);
    }
}

四、ThreadLocal原理总结

1. ThreadLocal的主要原理在于ThreadLocalMap的使用

每个线程在获取和设置线程局部变量时,都会操作自己的ThreadLocalMap。线程局部变量的值存储在ThreadLocalMap中的Entry对象中,每个Entry对象包含一个ThreadLocal实例和该线程局部变量的值。

2. 当调用ThreadLocal的get()方法时

它会先获取当前线程,然后从当前线程的ThreadLocalMap中获取ThreadLocal实例对应的Entry对象。如果Entry对象存在,则返回该Entry对象中存储的线程局部变量的值;如果Entry对象不存在,则返回null。

3. 当调用ThreadLocal的set()方法时

它会先获取当前线程,然后将ThreadLocal实例和要设置的值封装成一个Entry对象,再将该Entry对象存放到当前线程的ThreadLocalMap中。

4. 当线程结束时

ThreadLocalMap中的Entry对象会被垃圾回收器自动清除,从而防止内存泄漏。

通过ThreadLocal的实现原理,我们可以在多线程环境下实现线程间的数据隔离,每个线程都可以独立地访问自己的线程局部变量,互不干扰。这在一些需要在多个线程间共享数据的场景下十分有用,可以提高代码的并发性和线程安全性。

五、优秀的设计总结

1. 弱引用防内存泄漏:

通过在 Entry 类中使用 WeakReference<ThreadLocal<?>>,防止了ThreadLocal与Entry循环引用导致可能出现的内存泄漏

2. 懒初始化:

ThreadLocal内部使用了懒初始化的机制,在第一次获取数据时才会进行初始化。这种方式可以避免不必要的初始化操作,提高性能。

3. 共享数据的隔离:

ThreadLocal可以为每个线程提供独立的数据副本,这样每个线程都可以独立地操作自己的数据,而不会干扰其他线程的数据。这种隔离性有助于避免多线程环境下的数据竞争和线程安全问题。

六、ThreadLocal使用示例

ThreadLocal多线程数据隔离示例

public class ThreadLocalDemo {

    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        // 创建两个线程,并启动
        Thread thread1 = new Thread(() -> {
            // 设置线程1的变量值为1
            threadLocal.set(1);

            // 获取线程1的变量值
            System.out.println("线程1的变量值:" + threadLocal.get());
        });

        Thread thread2 = new Thread(() -> {
            // 设置线程2的变量值为2
            threadLocal.set(2);

            // 获取线程2的变量值
            System.out.println("线程2的变量值:" + threadLocal.get());
        });

        thread1.start();
        thread2.start();
    }
}
 

最后打印结果:

线程1的变量值:1
线程2的变量值:2

由此我们可以得出结果:多线程并发场景,每个线程通过ThreadLocal设置的变量是独有的,并不会被其他线程读取到

ThreadLocal多线程操作同一数据错误示例

public class ThreadLocalSyncExample {

    // 创建一个 ThreadLocal 对象
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) {
        // 设置初始值
        threadLocal.set(0);

        // 创建两个线程并启动
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                incrementAndPrint();
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                incrementAndPrint();
            }
        });

        thread1.start();
        thread2.start();
    }

    private static synchronized void incrementAndPrint() {
        // 获取当前线程的变量值并加1
        int value = threadLocal.get();
        threadLocal.set(value + 1);
        System.out.println(Thread.currentThread().getName() + ": " + threadLocal.get());
    }
}
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值