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

相关文章

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很

Spring事务中@Transactional注解不生效的原因分析与解决

《Spring事务中@Transactional注解不生效的原因分析与解决》在Spring框架中,@Transactional注解是管理数据库事务的核心方式,本文将深入分析事务自调用的底层原理,解释为... 目录1. 引言2. 事务自调用问题重现2.1 示例代码2.2 问题现象3. 为什么事务自调用会失效3

找不到Anaconda prompt终端的原因分析及解决方案

《找不到Anacondaprompt终端的原因分析及解决方案》因为anaconda还没有初始化,在安装anaconda的过程中,有一行是否要添加anaconda到菜单目录中,由于没有勾选,导致没有菜... 目录问题原因问http://www.chinasem.cn题解决安装了 Anaconda 却找不到 An

Spring定时任务只执行一次的原因分析与解决方案

《Spring定时任务只执行一次的原因分析与解决方案》在使用Spring的@Scheduled定时任务时,你是否遇到过任务只执行一次,后续不再触发的情况?这种情况可能由多种原因导致,如未启用调度、线程... 目录1. 问题背景2. Spring定时任务的基本用法3. 为什么定时任务只执行一次?3.1 未启用

Python异步编程中asyncio.gather的并发控制详解

《Python异步编程中asyncio.gather的并发控制详解》在Python异步编程生态中,asyncio.gather是并发任务调度的核心工具,本文将通过实际场景和代码示例,展示如何结合信号量... 目录一、asyncio.gather的原始行为解析二、信号量控制法:给并发装上"节流阀"三、进阶控制

Redis中高并发读写性能的深度解析与优化

《Redis中高并发读写性能的深度解析与优化》Redis作为一款高性能的内存数据库,广泛应用于缓存、消息队列、实时统计等场景,本文将深入探讨Redis的读写并发能力,感兴趣的小伙伴可以了解下... 目录引言一、Redis 并发能力概述1.1 Redis 的读写性能1.2 影响 Redis 并发能力的因素二、

C++ 各种map特点对比分析

《C++各种map特点对比分析》文章比较了C++中不同类型的map(如std::map,std::unordered_map,std::multimap,std::unordered_multima... 目录特点比较C++ 示例代码 ​​​​​​代码解释特点比较1. std::map底层实现:基于红黑

Java使用多线程处理未知任务数的方案介绍

《Java使用多线程处理未知任务数的方案介绍》这篇文章主要为大家详细介绍了Java如何使用多线程实现处理未知任务数,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 知道任务个数,你可以定义好线程数规则,生成线程数去跑代码说明:1.虚拟线程池:使用 Executors.newVir

Spring、Spring Boot、Spring Cloud 的区别与联系分析

《Spring、SpringBoot、SpringCloud的区别与联系分析》Spring、SpringBoot和SpringCloud是Java开发中常用的框架,分别针对企业级应用开发、快速开... 目录1. Spring 框架2. Spring Boot3. Spring Cloud总结1. Sprin

Spring 中 BeanFactoryPostProcessor 的作用和示例源码分析

《Spring中BeanFactoryPostProcessor的作用和示例源码分析》Spring的BeanFactoryPostProcessor是容器初始化的扩展接口,允许在Bean实例化前... 目录一、概览1. 核心定位2. 核心功能详解3. 关键特性二、Spring 内置的 BeanFactory