【多线程与高并发之ThreadLocal】——ThreadLocal源码分析

2024-08-26 00:48

本文主要是介绍【多线程与高并发之ThreadLocal】——ThreadLocal源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这里写目录标题

  • 前言
  • 总体UML图
    • ThreadLocal
      • 取值
      • 赋值
      • 移除
    • 图解ThreadLocal
    • ThreadLocalMap
      • 获取Key为ThreadLocal的Entry值
      • 给Key为ThreadLocal的Entry赋值
      • 移除Entry
    • SuppliedThreadLocal
  • 总结

前言

前面讲了ThreadLocal的基本知识,下面我们对ThreadLocal的源码进行分析。

总体UML图

我们首先看下ThreadLocal这个类的类图。
ThreadLocal类图
如图所示:ThreadLocal有两个内部类,ThreadLocalMap和SuppliedThreadLocal。

  • ThreadLocalMap,这个类本质上是一个map,和HashMap之类的实现相似,依然是key-value的形式,其中有一个内部类Entry,其中key可以看做是ThreadLocal实例,实际上是持有ThreadLocal实例的弱引用(下面讲ThreadLocalMap的时候我们会讲到为什么会是弱引用)。
  • SuppliedThreadLocal是JDK8新增的内部类,扩展了ThreadLocal的初始化值的方法,允许使用JDK8新增的Lambda表达式赋值。需要注意的是,函数式接口Supplier不允许为null。

ThreadLocal

根据ThreadLocal类的源码我们可以看出ThreadLocal类的主要方法有:获取get(),赋值set(T),移除remove()。下面我们依次讲解下这三个核心方法。

取值

先看下源码:

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

get()方法的流程如下:

  1. 获取当前线程t;
  2. 获取到当前线程t 的成员变量ThreadLocalMap;
 /*** 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;}
  1. 如果ThreadLocalMap不为null,从ThreadLocalMap中获取当前线程为key的Entry,如果Entry不为null时,则返回该Entry的value值。
  2. 如果ThreadLocalMap为null或者Entry为null,返回setInitialValue()的值。setInitialValue()调用重写的initialValue()返回新值(如果没有重写initialValue将返回默认值null),并将新值存入当前线程的ThreadLocalMap(如果当前线程没有ThreadLocalMap,会先创建一个)。
  /*** 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);elsecreateMap(t, value);return 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);}

赋值

源码:

  /*** 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);elsecreateMap(t, value);}

void set(T) 和setInitialValue类似,将新值存入当前线程的ThreadLocalMap(如果当前线程没有ThreadLocalMap,会先创建一个)。

移除

源码:

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

remove()方法是获取当前线程的ThreadLocalMap,若map不为空,则调用ThreadLocalMap的remove()方法移除当前ThreadLocal作为key的键值对。

图解ThreadLocal

让我们用一张图来了解下ThreadLocal,每个线程可能会有多个ThreadLocal,而每个线程中的ThreadLocal都会存放于同一个ThreadLocalMap中。但为避免占用空间较大或生命周期较长的数据常驻于内存引发一系列问题,hash table的key是弱引用WeakReferences。当空间不足时,会清理未被引用的entry。
在这里插入图片描述

ThreadLocalMap

ThreadLocalMap作为存储当前线程本地变量的定制化Map,仅有ThreadLocal类对其有操作权限,此定制化Map是Thread的私有属性。为避免占用空间较大或生命周期较长的数据常驻于内存引发一系列问题,hash table的key是弱引用WeakReferences。当空间不足时,会清理未被引用的entry。
内部类Entry源码如下:

 /*** 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的Key为ThreadLocal,value为object。
接下来,我们来分析下ThreadLocalMap中的getEntry(ThreadLocal<?> key) ,set(ThreadLocal<?> key, Object value) 和remove(ThreadLocal<?> key) 三个方法。

获取Key为ThreadLocal的Entry值

源码如下:

 /*** 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;elsereturn getEntryAfterMiss(key, i, e);}

getEntry流程如下:

  1. 计算Entry数组的下标索引值index:key.threadLocalHashCode & (table.length - 1);
  2. 获取索引对应的Entry;
  3. 如果返回节点entry 有值且其key未冲突(只有1个entry返回的key等于传入的key),则直接返回该entry;
  4. 返回entry为空或键冲突,则调用getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e)方法返回entry。

下面我们来看下getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) 这个方法做了哪些操作

getEntryAfterMiss处理那些getEntry时命中且有冲突的key。入参是当前ThreadLocal,key在数组的索引index,以及index对应的键值对。
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;while (e != null) {ThreadLocal<?> k = e.get();if (k == key)return e;if (k == null)expungeStaleEntry(i);elsei = nextIndex(i, len);e = tab[i];}return null;}

getEntryAfterMiss的流程如下:
当Entry不为空时,

  1. 获取entry的key;
  2. 如果key一致(内存地址=判断),则返回该entry;
  3. 如果key为null,则调用expungeStaleEntry方法擦除该entry;
  4. 其他情况则通过nextIndex方法获取下一个索引位置index;
  5. 获取新index处的entry,再次循环,直到定位到该key返回entry或者返回null。

expungeStaleEntry方法:只要key为null均会被擦除,使得对应value没有被引用,方便回收。
源码如下:

 /*** 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 staleSlottab[staleSlot].value = null;tab[staleSlot] = null;size--;// Rehash until we encounter nullEntry 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;}

给Key为ThreadLocal的Entry赋值

源码如下:

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

set流程如下:

  1. 计算Entry数组的下标索引值index:key.threadLocalHashCode & (len- 1);
  2. 当前index处已有entry ,并且Key相同,则更新value值;
  3. 出现过期数据 ,遍历清洗过期数据并在index处插入新数据,其他数据后移;
  4. 没有过期数据被清理且实际size超过扩容阈值,则首先调用expungeStaleEntries删除所有过期数据,如果清理数据后size>=threshold的3/4,进行2倍扩容。
    size:table的实际entry数量;
    扩容阈值threshold:table.length(默认16)大小的2/3;

移除Entry

移除ThreadLocal为key的Entry。
源码如下:

/*** 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.计算Entry数组的下标索引值index:key.threadLocalHashCode & (len- 1);
2.当前index处已有entry ,并且Key相同,则进行移除操作。

SuppliedThreadLocal

SuppliedThreadLocal是JDK8新增的内部类,扩展了ThreadLocal的初始化值的方法,允许使用JDK8新增的Lambda表达式赋值。需要注意的是,函数式接口Supplier不允许为null。

源码如下:

  /*** An extension of ThreadLocal that obtains its initial value from* the specified {@code Supplier}.*/static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {private final Supplier<? extends T> supplier;SuppliedThreadLocal(Supplier<? extends T> supplier) {this.supplier = Objects.requireNonNull(supplier);}@Overrideprotected T initialValue() {return supplier.get();}}

总结

看了类图,总结了源码之后,对于ThreadLocal有了一个更清晰的认识。ThreadLocalMap作为一个定制化的Map来存储当前线程的本地变量值,它和HashMap同样都是Key-Value型的键值对,但两者又有其不同。那两者具体有哪些相似和不同呢,期待我的下篇博客吧。

这篇关于【多线程与高并发之ThreadLocal】——ThreadLocal源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1107074

相关文章

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

Java多线程父线程向子线程传值问题及解决

《Java多线程父线程向子线程传值问题及解决》文章总结了5种解决父子之间数据传递困扰的解决方案,包括ThreadLocal+TaskDecorator、UserUtils、CustomTaskDeco... 目录1 背景2 ThreadLocal+TaskDecorator3 RequestContextH

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

C#多线程编程中导致死锁的常见陷阱和避免方法

《C#多线程编程中导致死锁的常见陷阱和避免方法》在C#多线程编程中,死锁(Deadlock)是一种常见的、令人头疼的错误,死锁通常发生在多个线程试图获取多个资源的锁时,导致相互等待对方释放资源,最终形... 目录引言1. 什么是死锁?死锁的典型条件:2. 导致死锁的常见原因2.1 锁的顺序问题错误示例:不同

浅析Rust多线程中如何安全的使用变量

《浅析Rust多线程中如何安全的使用变量》这篇文章主要为大家详细介绍了Rust如何在线程的闭包中安全的使用变量,包括共享变量和修改变量,文中的示例代码讲解详细,有需要的小伙伴可以参考下... 目录1. 向线程传递变量2. 多线程共享变量引用3. 多线程中修改变量4. 总结在Rust语言中,一个既引人入胜又可

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操

Redis主从/哨兵机制原理分析

《Redis主从/哨兵机制原理分析》本文介绍了Redis的主从复制和哨兵机制,主从复制实现了数据的热备份和负载均衡,而哨兵机制可以监控Redis集群,实现自动故障转移,哨兵机制通过监控、下线、选举和故... 目录一、主从复制1.1 什么是主从复制1.2 主从复制的作用1.3 主从复制原理1.3.1 全量复制

Redis主从复制的原理分析

《Redis主从复制的原理分析》Redis主从复制通过将数据镜像到多个从节点,实现高可用性和扩展性,主从复制包括初次全量同步和增量同步两个阶段,为优化复制性能,可以采用AOF持久化、调整复制超时时间、... 目录Redis主从复制的原理主从复制概述配置主从复制数据同步过程复制一致性与延迟故障转移机制监控与维