ThreadLocal概述

本文详细介绍了ThreadLocal的工作原理及其实现机制,包括如何通过ThreadLocalMap为每个线程提供独立的变量副本,以及可能导致的内存泄漏问题。

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

转载自http://blog.xiaohansong.com/2016/08/06/ThreadLocal-memory-leak/

ThreadLocal与线程同步机制不同,线程同步机制是多个线程共享同一个变量,而ThreadLocal是为每一个线程创建一个单独的变量副本,故而每个线程都可以独立地改变自己所拥有的变量副本,而不会影响其他线程所对应的副本。可以说ThreadLocal为多线程环境下变量问题提供了另外一种解决思路。

ThreadLocal定义了四个方法:

get():返回此线程局部变量的当前线程副本中的值。
initialValue():返回此线程局部变量的当前线程的“初始值”。
remove():移除此线程局部变量当前线程的值。
set(T value):将此线程局部变量的当前线程副本中的值设置为指定值。

ThreadLocal内部还有一个静态内部类ThreadLocalMap,该内部类才是实现线程隔离机制的关键,get()、set()、remove()都是基于该内部类操作。ThreadLocalMap提供了一种用键值对方式存储每一个线程的变量副本的方法,key为当前ThreadLocal对象,value则是对应线程的变量副本。

image

ThreadLocal的实现是这样的:每个Thread 维护一个 ThreadLocalMap 映射表,这个映射表的 key 是 ThreadLocal 实例本身,value 是真正需要存储的 Object。

也就是说 ThreadLocal 本身并不存储值,它只是作为一个 key 来让线程从 ThreadLocalMap 获取 value。值得注意的是图中的虚线,表示 ThreadLocalMap 是使用 ThreadLocal 的弱引用作为 Key 的,如果一个对象只有弱引用,那么它在 GC 时会被回收。

ThreadLocal源码解析

ThreadLocal虽然解决了这个多线程变量的复杂问题,但是它的源码实现却是比较简单的。ThreadLocalMap是实现ThreadLocal的关键,我们先从它入手。

ThreadLocalMap

ThreadLocalMap其内部利用Entry来实现key-value的存储,如下:

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

ThreadLocalMap的源码稍微多了点,我们就看两个最核心的方法set(ThreadLocal key, Object value)、getEntry()。

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

        // 如果key存在,则覆盖
        if (k == key) {
            e.value = value;
            return;
        }

        // 如果key==null,entry!=null,说明之前的ThreadLocal对象已经被回收。
        // 此时使用新元素替换掉旧元素,并且replaceStaleEntry还会删除其它部分旧条目。
        if (k == null) {
            replaceStaleEntry(key, value, i);
            return;
        }
    }

    tab[i] = new Entry(key, value);
    int sz = ++size;

    // cleanSomeSlots 清除陈旧的Entry(key == null)
    // 如果没有清理陈旧的 Entry 并且数组中的元素大于了阈值,则进行 rehash
    if (!cleanSomeSlots(i, sz) && sz >= threshold)
        rehash();
}
/**
 * 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();
    ThreadLocalMap map = getMap(t);//获取当前线程的ThreadLocalMap
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

/**
 * 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) {
    int i = key.threadLocalHashCode & (table.length - 1);
    Entry e = table[i];
    if (e != null && e.get() == key)
        return e;
    else
        return getEntryAfterMiss(key, i, e);
}

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

    while (e != null) {
        ThreadLocal<?> k = e.get();
        if (k == key) // 找到key,返回entry
            return e;
        if (k == null)//清除陈旧的Entry(key == null)
            expungeStaleEntry(i);
        else // 使用线性探测法找下一个位置
            i = nextIndex(i, len);
        e = tab[i];
    }
    return null;
}
内容概要:本文档是关于基于Tecnomatix的废旧智能手机拆解产线建模与虚拟调试的毕业设计任务书。研究内容主要包括:分析废旧智能手机拆解工艺流程;学习并使用Tecnomatix软件搭建拆解产线的三维模型,包括设备、输送装置等;进行虚拟调试以模拟各种故障情况,并对结果进行分析提出优化建议。研究周期为16周,涵盖了文献调研、拆解实验、软件学习、建模、调试和论文撰写等阶段。文中还提供了Python代码来模拟部分关键流程,如拆解顺序分析、产线布局设计、虚拟调试过程、故障模拟与分析等,并实现了结果的可视化展示。 适合人群:本任务书适用于机械工程、工业自动化及相关专业的本科毕业生,尤其是那些对智能制造、生产线优化及虚拟调试感兴趣的学生。 使用场景及目标:①帮助学生掌握Tecnomatix软件的应用技能;②通过实际项目锻炼学生的系统建模和虚拟调试能力;③培养学生解决复杂工程问题的能力,提高其对废旧电子产品回收再利用的认识和技术水平;④为后续的研究或工作打下坚实的基础,比如从事智能工厂规划、生产线设计与优化等工作。 其他说明:虽然文中提供了部分Python代码用于模拟关键流程,但完整的产线建模仍需借助Tecnomatix商业软件完成。此外,为了更好地理解和应用这些内容,建议学生具备一定的编程基础(如Python),并熟悉相关领域的基础知识。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值