【多线程与高并发之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

相关文章

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Javaee多线程之进程和线程之间的区别和联系(最新整理)

《Javaee多线程之进程和线程之间的区别和联系(最新整理)》进程是资源分配单位,线程是调度执行单位,共享资源更高效,创建线程五种方式:继承Thread、Runnable接口、匿名类、lambda,r... 目录进程和线程进程线程进程和线程的区别创建线程的五种写法继承Thread,重写run实现Runnab

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

python中Hash使用场景分析

《python中Hash使用场景分析》Python的hash()函数用于获取对象哈希值,常用于字典和集合,不可变类型可哈希,可变类型不可,常见算法包括除法、乘法、平方取中和随机数哈希,各有优缺点,需根... 目录python中的 Hash除法哈希算法乘法哈希算法平方取中法随机数哈希算法小结在Python中,

Java Stream的distinct去重原理分析

《JavaStream的distinct去重原理分析》Javastream中的distinct方法用于去除流中的重复元素,它返回一个包含过滤后唯一元素的新流,该方法会根据元素的hashcode和eq... 目录一、distinct 的基础用法与核心特性二、distinct 的底层实现原理1. 顺序流中的去重

关于MyISAM和InnoDB对比分析

《关于MyISAM和InnoDB对比分析》:本文主要介绍关于MyISAM和InnoDB对比分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录开篇:从交通规则看存储引擎选择理解存储引擎的基本概念技术原理对比1. 事务支持:ACID的守护者2. 锁机制:并发控制的艺

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Python主动抛出异常的各种用法和场景分析

《Python主动抛出异常的各种用法和场景分析》在Python中,我们不仅可以捕获和处理异常,还可以主动抛出异常,也就是以类的方式自定义错误的类型和提示信息,这在编程中非常有用,下面我将详细解释主动抛... 目录一、为什么要主动抛出异常?二、基本语法:raise关键字基本示例三、raise的多种用法1. 抛