ThreadLocal原理

本文深入解析了ThreadLocal的工作原理,包括其内部数据结构ThreadLocalMap及其Entry实现方式,详细阐述了set、get等核心方法的运作流程,并展示了如何通过弱引用避免内存泄漏。

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

threadLocal理解

线程与线程变量的绑定,方便线程变量的隔离

ThreadLocal数据结构

ThreadLocal数据结构图

 Thread类中引用了ThreadLocalMap

 /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

ThreadLocal类中定义了静态类ThreadLocalMap

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 initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        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

ThreadLocalMap中定义了静态类Entry

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

ThreadLocal常用方法

set、get、remove

ThreadLocal的set方法

 public void set(T value) {
        //获取当前线程
        Thread t = Thread.currentThread();
        //获取线程的threadlocals
        ThreadLocalMap map = getMap(t);
        if (map != null)
            //map不为空则设置值
            map.set(this, value);
        else
            //map为空创建ThreadLocalMap并赋值
            createMap(t, value);
 }
//获取线程的threadlocals
ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
}
//ThreadLocalMap类中放值
 private void set(ThreadLocal<?> key, Object value) {

            Entry[] tab = table;
            int len = tab.length;
            //计算该ThreadLocal对象在table数组中的下标
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();
                //如果保存过该唐浩然的local对象,则覆盖
                if (k == key) {
                    e.value = value;
                    return;
                }
                //如果该Entry对应的ThreadLocal对象为空,清除脏数据后放值
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }
            //创建新的Entry
            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
}

rehash方法进行数组扩容

private void rehash() {
            //清除脏数据,修改size的值
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            //使用较低的阈值
            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);
            }
}
//清理脏数据方法
private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            //将该节点置空
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();
                //节点对应的key,即threadlocal对象为null,则将值也置为null,size减一
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    //计算下标值
                    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.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
}

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();
                    //该entry对应的threadLocal为null,则将对应的value也设置为null,方便GC
                    if (k == null) {
                        e.value = null; // Help the GC
                    } else {
                        //计算新数组的下标值
                        int h = k.threadLocalHashCode & (newLen - 1);
                        //如果对应的下标值已经存有数据,则继续往后查询,知道找到为null的entry
                        //来保存数据
                        while (newTab[h] != null)
                            h = nextIndex(h, newLen);
                        //保存数据
                        newTab[h] = e;
                        count++;
                    }
                }
            }
            //设置新的阈值
            setThreshold(newLen);
            //修改size值
            size = count;
            //更新table数组
            table = newTab;
}
//设置阈值
private void setThreshold(int len) {
            //设置阈值为数组长度的2/3
            threshold = len * 2 / 3;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值