[NIO与Netty] ThreadLocal详解

本文详细解析了Java中ThreadLocal的工作原理,包括基本使用、实现机制及源码分析,阐述了如何通过ThreadLocal实现线程局部变量,确保数据的线程隔离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ThreadLocal实现了Java中线程局部变量。所谓线程局部变量就是保存在每个线程中独有的一些数据,我们知道一个进程中的所有线程是共享该进程的资源的,线程对进程中的资源进行修改会反应到该进程中的其他线程上,如果我们希望一个线程对资源的修改不会影响到其他线程,那么就需要将该资源设为线程局部变量的形式。

ThreadLocal的基本使用

如下示例所示,定义两个ThreadLocal变量,然后分别在主线程和子线程中对线程局部变量进行修改,然后分别获取线程局部变量的值:

public class ThreadLocalTest {

    private static ThreadLocal<String> threadLocal1 = ThreadLocal.withInitial(() -> "threadLocal1 first value");
    private static ThreadLocal<String> threadLocal2 = ThreadLocal.withInitial(() -> "threadLocal2 first value");

    public static void main(String[] args) throws Exception{


        Thread thread = new Thread(() -> {

            System.out.println("================" + Thread.currentThread().getName() + " enter=================");

            // 子线程中打印出初始值
            printThreadLocalInfo();

            // 子线程中设置新值
            threadLocal1.set("new thread threadLocal1 value");
            threadLocal2.set("new thread threadLocal2 value");

            // 子线程打印出新值
            printThreadLocalInfo();

            System.out.println("================" + Thread.currentThread().getName() + " exit=================");
        });

        thread.start();
        // 等待新线程执行
        thread.join();
        
        // 在main线程打印threadLocal1和threadLocal2,验证子线程对这两个变量的修改是否会影响到main线程中的这两个值
        printThreadLocalInfo();
        // 在main线程中给threadLocal1和threadLocal2设置新值
        threadLocal1.set("main threadLocal1 value");
        threadLocal2.set("main threadLocal2 value");
        // 验证main线程中这两个变量是否为新值
        printThreadLocalInfo();
    }

    private static void printThreadLocalInfo() {
        System.out.println(Thread.currentThread().getName() + ": " + threadLocal1.get());
        System.out.println(Thread.currentThread().getName() + ": " + threadLocal2.get());
    }
}

运行结果如下:

================Thread-0 enter=================
Thread-0: threadLocal1 first value
Thread-0: threadLocal2 first value
Thread-0: new thread threadLocal1 value
Thread-0: new thread threadLocal2 value
================Thread-0 exit=================
main: threadLocal1 first value
main: threadLocal2 first value
main: main threadLocal1 value
main: main threadLocal2 value

如果子线程对threadLocal1threadLocal2的修改会影响到main线程中的threadLocal1threadLocal2,那么在main线程第一次printThreadLocalInfo();打印出的应该是修改后的新值,即为new thread threadLocal1 valuenew thread threadLocal2 value和,但实际打印结果并不是这样,说明在新线程中对threadLocal1threadLocal2的修改并不会影响到main线程中的这两个变量,似乎main线程中的threadLocal1threadLocal2作用域仅局限于main线程,新线程中的threadLocal1threadLocal2作用域仅局限于新线程,这就是线程局部变量的由来。

ThreadLocal实现原理

如下图所示
ThreadLocal实现原理
每个线程对象里会持有一个java.lang.ThreadLocal.ThreadLocalMap类型的threadLocals成员变量,而ThreadLocalMap里有一个java.lang.ThreadLocal.ThreadLocalMap.Entry[]类型的table成员,这是一个数组,数组元素是Entry类型,Entry中相当于有一个keyvaluekey指向所有线程共享的java.lang.ThreadLocal对象,value指向各线程私有的变量,这样保证了线程局部变量的隔离性,每个线程只是读取和修改自己所持有的那个value对象,相互之间没有影响。

源码分析(基于openjdk11)

源码包括ThreadLocalThreadLocalMapThreadLocalMapThreadLocal内定义的一个静态内部类,用于存储实际的数据。当调用ThreadLocalget或者set方法时都有可能创建当前线程的threadLocals成员(ThreadLocalMap类型)。

get方法:

ThreadLocal的get方法定义如下

    /**
     * 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();
        // 获取当前线程的threadLocals成员变量,这是一个ThreadLocalMap
        ThreadLocalMap map = getMap(t);
        // threadLocals不为null则直接从threadLocals中取出ThreadLocal
        // 对象对应的值
        if (map != null) {
        	// 从map中获取当前ThreadLocal对象对应Entry对象
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
            	// 获取ThreadLocal对象对应的value值
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        // threadLocals为null,则需要创建ThreadLocalMap对象并赋给
        // threadLocals,将当前ThreadLocal对象作为key,调用initialValue
        // 获得的初始值作为value,放置到threadLocals的entry中;
        // 或者threadLocals不为null,但在threadLocals中未
        // 找到当前ThreadLocal对象对应的entry,则需要向threadLocals添加新的
        // entry,该entry以当前的ThreadLocal对象作为key,调用initialValue
        // 获得的值作为value
        return setInitialValue();
    }
    /**
     * 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;
    }

ThreadthreadLocals为null,或者在ThreadthreadLocals中未找到当前ThreadLocal对象对应的entry,则进入到setInitialValue方法;否则进入到ThreadLocalMapgetEntry方法。

setInitialValue方法

定义如下:

    private T setInitialValue() {
    	// 获取初始值,如果我们在定义ThreadLocal对象时实现了ThreadLocal
    	// 的initialValue方法,就会调用我们自定义的方法来获取初始值,否则
    	// 使用initialValue的默认实现返回null值
        T value = initialValue();
        Thread t = Thread.currentThread();
        // 获取当前线程的threadLocals成员
        ThreadLocalMap map = getMap(t);
        if (map != null) {
        	// 若threadLocals存在则将ThreadLocal对象对应的value设置为初始值
            map.set(this, value);
        } else {
        	// 否则创建threadLocals对象并设置初始值
            createMap(t, value);
        }
        if (this instanceof TerminatingThreadLocal) {
            TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
        }
        return value;
    }

createMap方法实现

    /**
     * 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) {
    	// 创建一个ThreadLocalMap对象,用当前ThreadLocal对象和初始值value来
    	// 构造ThreadLocalMap中table的第一个entry。ThreadLocalMap对象赋
    	// 给线程的threadLocals成员
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

ThreadLocalMap的构造方法定义如下:

        /**
         * 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.
         */
        ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
        	// 构造table数组,数组大小为INITIAL_CAPACITY
            table = new Entry[INITIAL_CAPACITY];
            // 计算key(ThreadLocal对象)在table中的索引
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            // 用ThreadLocal对象和value来构造entry对象,并放到table的第i个位置
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            // 设置table的阈值,当table中元素个数超过该阈值时需要对table
            // 进行resize,通常在调用ThreadLocalMap的set方法时会发生resize
            setThreshold(INITIAL_CAPACITY);
        }
        /**
         * Set the resize threshold to maintain at worst a 2/3 load factor.
         */
        private void setThreshold(int len) {
            threshold = len * 2 / 3;
        }

这里firstKey.threadLocalHashCode是ThreadLocal中定义的一个hashcode,使用该hashcode进行hash运算从而找到该ThreadLocal对象对应的entry在table中的索引。

getEntry方法

定义如下:

        /**
         * 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
         */
        private Entry getEntry(ThreadLocal<?> key) {
        	// 根据ThreadLocal的hashcode计算该ThreadLocal对象在table中的位置
            int i = key.threadLocalHashCode & (table.length - 1);
            Entry e = table[i];
            // e为null则table不存在key对应的entry;
            // e.get() != key 可能是由于hash冲突导致key对应的entry在table
            // 的另外一个位置,需要继续查找
            if (e != null && e.get() == key)
                return e;
            else
            	// e==null或者e.get() != key 继续查找key对应的entry
                return getEntryAfterMiss(key, i, e);
        }

getEntryAfterMiss方法定义如下:

        /**
         * Version of getEntry method for use when key is not found in
         * its direct hash slot.
         * 
         * @param  key the thread local object
         * @param  i the table index for key's hash code
         * @param  e the entry at table[i]
         * @return the entry associated with key, or null if no such
         */
        private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e){
            Entry[] tab = table;
            int len = tab.length;
			
			// 从table的第i个位置一直往后找,直到找到键为key的entry为止
            while (e != null) {
                ThreadLocal<?> k = e.get();
                // 若k==key,则找到了entry
                if (k == key)
                    return e;
                // k == null 需要删除该entry
                if (k == null)
                    expungeStaleEntry(i);
                // k != key && k != null 继续往后寻找,nextIndex就是取(i+1)
                // 即table中第(i+1)个位置的entry
                else
                    i = nextIndex(i, len);
                e = tab[i];
            }
            return null;
        }

expungeStaleEntry方法删除key为null的entry,删除后对staleSlot位置的entry和其后第一个为null的entry之间的entry进行一个rehash操作,rehash的目的是降低table发生碰撞的概率:

        /**
         * Expunge a stale entry by rehashing any possibly colliding entries
         * lying between staleSlot and the next null slot.  This also expunges
         * any other stale entries encountered before the trailing null.  See
         * Knuth, Section 6.4
         *
         * @param staleSlot index of slot known to have null key
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         */
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            // 删除staleSlot位置的entry
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            // table中元素个数减一
            size--;

            // Rehash until we encounter null
            // 将table中staleSlot处entry和下一个为null的entry之间的
            // entry重新进行hash放置到新的位置
            // 遇到的entry的key为null则删除该entry
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                // e是下一个entry
                ThreadLocal<?> k = e.get();
                if (k == null) {
                	// 若entry的key为null,则删除
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                	// entry的key不为null,需要将entry放到新的位置
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        // tab[h]不为null则发生冲突,继续寻找下一个位置
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }

set方法

ThreadLocal的set方法定义如下:

    /**
     * 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();
        // 获取当前线程的threadLocals
        ThreadLocalMap map = getMap(t);
        // threadLocals不为null直接设置新值
        if (map != null) {
            map.set(this, value);
        } else {
        	// threadLocals为null则需要创建ThreadLocalMap对象并赋给
        	// Thread的threadLocals成员
            createMap(t, value);
        }
    }

createMap前面已经分析过,接下来分析ThreadLocalMap的set方法

ThreadLocalMap的set方法

ThreadLocalMap的set方法定义如下,将当前的ThreadLocal对象作为key,传入的value为值,用key和value创建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;
            // 用key计算entry在table中的位置
            int i = key.threadLocalHashCode & (len-1);

			// tab[i]不为null的话,则第i个位置已经存在有效的entry,需要继续
			// 往后寻找新的位置
            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();
				
				// 找到与key相同的entry,直接更新value的值
                if (k == key) {
                    e.value = value;
                    return;
                }
				
				// 遇到key为null的entry,删除该entry
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

			// 此时第i个位置entry为null,将新entry放置到这个位置
            tab[i] = new Entry(key, value);
            int sz = ++size;
            // 试图清除无效的entry,若清除失败并且table中有效entry个数
            // 大于threshold,这进行rehash操作
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
replaceStaleEntry方法

replaceStaleEntry的作用是用set方法传过来的key和value构造entry,将这个entry放到staleSlot后面的某个位置:

       /**
         * 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).
            // 从staleSlot往前找到第一个key为null的entry的位置
            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
            // 从staleSlot位置往后寻找
            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.
                // 若k与key相同,则直接更新value
                if (k == key) {
                    e.value = value;
					// 将原来staleSlot位置的entry放置到第i个位置,此时tab[i]处的entry的key为null
                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists
                    // 从staleSlot处往前未找到key为null的entry
                    if (slotToExpunge == staleSlot)
                    	// tab[i]处entry的key为null,也即tab[slotToExpunge]处entry的key为null
                        slotToExpunge = i;
                    // 清除slotToExpunge位置的entry并进行rehash操作.....
                    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);
        }

以下源码只可意会,不可言传…不再做说明

cleanSomeSlots方法

cleanSomeSlots方法:

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

rehash方法:

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

expungeStaleEntries方法:

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

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 (Entry e : oldTab) {
                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;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值