ThreadLocal 源码分析

ThreadLocal用于多线程环境下为每个线程提供独立的变量副本,确保线程间数据隔离。本文详细解析了ThreadLocal的工作原理,包括其内部实现机制、源码分析及应用场景。

Threadlocal 主要用于在多线程的情况下,每个线程可以保存一份本地的变量,该变量在线程之间相互独立,互不影响,并伴随着该线程的运行过程可以随时取出。

应用场景:比如,在web系统中,每个用户进行访问都有各自的不同的用户信息,可以在访问接收的时候做一个拦截器,把用户的信息放入到threadlocal中,在该线程的整个流程中,可以取出当前用户的相关信息,并且和其他线程不相互影响。

原理:每个线程都有一个threadlocalMap对象,在向threadlocal放入变量的时候,实际上是向每个线程的threadlocalMap中放入变量,放入的变量是key value形式的,其中key是当前的threadLocal对象,value是放入的变量。threadlocalMap中有个Entity的kev value 数组,该entity其中的key是弱引用,也就是存放threadLocal对象的地方。

源码分析

首先从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();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

(1)先获取当前的线程

(2)然后获取当前线程的ThreadLocalMap        ThreadLocalMap map = getMap(t);

如果是第一次调用该方法,之前没有set过值,那么map应该为null。会调用 setInitialValue()方法;

/**
 * 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();
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
    return value;
}

(1)初始化的时候value 是为null ,map根据上面第一次调用的话为null

(2)所有会调用createMap(t, value)方法

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

(1)获取当前线程threadLocalMap 然后new 了一个

/**
 * 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 = new Entry[INITIAL_CAPACITY];
    int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    size = 1;
    setThreshold(INITIAL_CAPACITY);
}

(1)该构造方法为threadLocalMap内部的构造方法,主要的值存放在table数组中

(2)int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);  获取数组的下标,& (INITIAL_CAPACITY - 1)相当于对数组的初始容量取模,下标值一定是在数组容量范围内的。

(3)因为是第一次初始化,数组的大小为1.

(4) setThreshold(INITIAL_CAPACITY); 设置重新分配数组的空间的阀值,为数组大小的2/3,超过这个数组,从新分配空间。

public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

接下来看最开始的那段代码 ,假设不是第一次调用,当map不为空的时候 ,会走到

ThreadLocalMap.Entry e = map.getEntry(this); 这段代码

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

(1)if (e != null && e.get() == key)  如果当前位置值存在,并且key也相等,直接返回该值。

(2)存在一种情况,在放入值得时候,key的位置i已经存在了,则用线性探测法,去找下一个位置,直到找到不存在的位置,

所以上面的判断if不成立的时候,会调用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)
            return e;
        if (k == null)
            expungeStaleEntry(i);
        else
            i = nextIndex(i, len);
        e = tab[i];
    }
    return null;
}

(1)从 i的位置向下遍历整张表,因为table不会一定会有为null的位置,所以找不到则返回null,找到key相等的值则直接返回。

(2)因为key 为弱引用,所有当key为空的时候,调用方法expungeStaleEntry(i) 情况value的值,并且遍历整张表,清空所有key为null的值。

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

接下来我们看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();
    ThreadLocalMap map = getMap(t);
    if (map != null)
        map.set(this, value);
    else
        createMap(t, value);
}

(1)第一次set的时候同理上面已经说过createMap相关

(2)我们只看不是第一次的情况,这时候map不为空,该方法会调用map.set(this, 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();
}
(1)查找到有相同的key 则value进行覆盖,没有相同的key ,则在 i的位置创建一个新的entry

接下来看remove方法

/**
 * Removes the current thread's value for this thread-local
 * variable.  If this thread-local variable is subsequently
 * {@linkplain #get read} by the current thread, its value will be
 * reinitialized by invoking its {@link #initialValue} method,
 * unless its value is {@linkplain #set set} by the current thread
 * in the interim.  This may result in multiple invocations of the
 * {@code initialValue} method in the current thread.
 *
 * @since 1.5
 */
 public void remove() {
     ThreadLocalMap m = getMap(Thread.currentThread());
     if (m != null)
         m.remove(this);
 }

直接可以看m.remove(this)方法

/**
 * Remove the entry for key.
 */
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);
            return;
        }
    }
}

(1)直接遍历table,找到当前的key在table中位置

(2)e.clear() 把key 弱引用置为null

(3)expungeStaleEntry(i) 把所有key为null的 value值清空


ThreadLocal 可能写的不是很好,还有一些地方没有看的很明白,就没有在本文中细说。



下载方式:https://pan.quark.cn/s/a4b39357ea24 在纺织制造领域中,纱线的品质水平对最终制成品的整体质量具有决定性作用。 鉴于消费者对于产品规格和样式要求的不断变化,纺织制造工艺的执行过程日益呈现为一种更为复杂的操作体系,进而导致对纱线质量进行预测的任务变得更加困难。 在众多预测技术中,传统的预测手段在面对多变量间相互交织的复杂关系时,往往显得力不从心。 因此,智能计算技术在预测纱线质量的应用场景中逐渐占据核心地位,其中人工神经网络凭借其卓越的非线性映射特性以及自适应学习机制,成为了众多预测方法中的一种重要选择。 在智能计算技术的范畴内,粒子群优化算法(PSO)和反向传播神经网络(BP神经网络)是两种被广泛采用的技术方案。 粒子群优化算法是一种基于群体智能理念的优化技术,它通过模拟鸟类的群体觅食行为来寻求最优解,该算法因其操作简便、执行高效以及具备优秀的全局搜索性能,在函数优化、神经网络训练等多个领域得到了普遍应用。 反向传播神经网络则是一种由多层节点构成的前馈神经网络,它通过误差反向传播的机制来实现网络权重和阈值的动态调整,从而达成学习与预测的目标。 在实际操作层面,反向传播神经网络因其架构设计简洁、实现过程便捷,因此被广泛部署于各类预测和分类任务之中。 然而,该方法也存在一些固有的局限性,例如容易陷入局部最优状态、网络收敛过程缓慢等问题。 而粒子群优化算法在参与神经网络优化时,能够显著增强神经网络的全局搜索性能并提升收敛速度,有效规避神经网络陷入局部最优的困境。 将粒子群优化算法与反向传播神经网络相结合形成的PSO-BP神经网络,通过运用粒子群优化算法对反向传播神经网络的权值和阈值进行精细化调整,能够在预测纱线断裂强度方面,显著提升预测结果的...
植物实例分割数据集 一、基础信息 数据集名称:植物实例分割数据集 图片数量: - 训练集:9,600张图片 - 验证集:913张图片 - 测试集:455张图片 总计:10,968张图片 分类类别:59个类别,对应数字标签0至58,涵盖多种植物状态或特征。 标注格式:YOLO格式,适用于实例分割任务,包含多边形标注点。 数据格式:图像文件,来源于植物图像数据库,适用于计算机视觉任务。 二、适用场景 • 农业植物监测AI系统开发:数据集支持实例分割任务,帮助构建能够自动识别植物特定区域并分类的AI模型,辅助农业专家进行精准监测和分析。 • 智能农业应用研发:集成至农业管理平台,提供实时植物状态识别功能,为作物健康管理和优化种植提供数据支持。 • 学术研究与农业创新:支持植物科学与人工智能交叉领域的研究,助力发表高水平农业AI论文。 • 农业教育与培训:数据集可用于农业院校或培训机构,作为学生学习植物图像分析和实例分割技术的重要资源。 三、数据集优势 • 精准标注与多样性:标注采用YOLO格式,确保分割区域定位精确;包含59个类别,覆盖多种植物状态,具有高度多样性。 • 数据量丰富:拥有超过10,000张图像,大规模数据支持模型充分学习和泛化。 • 任务适配性强:标注兼容主流深度学习框架(如YOLO、Mask R-CNN等),可直接用于实例分割任务,并可能扩展到目标检测或分类等任务。
室内物体实例分割数据集 一、基础信息 • 数据集名称:室内物体实例分割数据集 • 图片数量: 训练集:4923张图片 验证集:3926张图片 测试集:985张图片 总计:9834张图片 • 训练集:4923张图片 • 验证集:3926张图片 • 测试集:985张图片 • 总计:9834张图片 • 分类类别: 床 椅子 沙发 灭火器 人 盆栽植物 冰箱 桌子 垃圾桶 电视 • 床 • 椅子 • 沙发 • 灭火器 • 人 • 盆栽植物 • 冰箱 • 桌子 • 垃圾桶 • 电视 • 标注格式:YOLO格式,包含实例分割的多边形标注,适用于实例分割任务。 • 数据格式:图片为常见格式如JPEG或PNG。 二、适用场景 • 实例分割模型开发:适用于训练和评估实例分割AI模型,用于精确识别和分割室内环境中的物体,如家具、电器和人物。 • 智能家居与物联网:可集成到智能家居系统中,实现自动物体检测和场景理解,提升家居自动化水平。 • 机器人导航与交互:支持机器人在室内环境中的物体识别、避障和交互任务,增强机器人智能化应用。 • 学术研究与教育:用于计算机视觉领域实例分割算法的研究与教学,助力AI模型创新与验证。 三、数据集优势 • 类别多样性:涵盖10个常见室内物体类别,包括家具、电器、人物和日常物品,提升模型在多样化场景中的泛化能力。 • 精确标注质量:采用YOLO格式的多边形标注,确保实例分割边界的准确性,适用于精细的物体识别任务。 • 数据规模充足:提供近万张标注图片,满足模型训练、验证和测试的需求,支持稳健的AI开发。 • 任务适配性强:标注格式兼容主流深度学习框架(如YOLO系列),便于快速集成到实例分割项目中,提高开发效率。
【鲁棒优化、大M法、C&CG算法】计及风、光、负荷不确定性两阶段鲁棒优化(Matlab代码实现)内容概要:本文介绍了基于Matlab代码实现的计及风、光、负荷不确定性的两阶段鲁棒优化方法,重点应用鲁棒优化理论、大M法和C&CG算法解决电力系统中可再生能源出力与负荷需求波动带来的不确定性问题。文中详细阐述了两阶段鲁棒优化模型的构建过程,第一阶段做出预决策,第二阶段在不确定性显现后进行调整,并通过列与约束生成(C&CG)算法迭代求解,结合大M法将条件约束转化为线性形式,提升模型求解效率。该方法适用于含高比例可再生能源的电力系统调度与规划,具备较强的实用性与扩展性。; 适合人群:具备一定电力系统基础知识和Matlab编程能力的研究生、科研人员及从事能源系统优化工作的工程师。; 使用场景及目标:①用于解决风电、光伏出力及负荷需求不确定环境下的电力系统优化调度问题;②支撑微电网、综合能源系统等场景下的鲁棒决策制定,提升系统运行的安全性与经济性;③为学术研究提供可复现的两阶段鲁棒优化建模范例。; 阅读建议:建议读者结合提供的Matlab代码逐模块理解模型实现细节,重点关注不确定性建模、大M法转化技巧及C&CG算法的迭代流程,宜在掌握基础优化理论的前提下进行推导与仿真验证。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值