java.lang.InheritableThreadLocal

2023-11-08 19:38

本文主要是介绍java.lang.InheritableThreadLocal,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

ThreadLocal是一个线程局部变量类,他是跟当前线程绑定的,线程与线程之间是相互不影响的。也就是在一个线程中通过ThreadLocal进行set值之后,其他线程get是get不到的,只能自己线程进行get。 但是有时候我们想主线程set值,子线程都能取到,这样的话,ThreadLocal就不适用了。幸好java提供了一个类InheritableThreadLocal,它继承自ThreadLocal, 而且Thread类中也定义了相关的变量,使得这个场景得以实现。

直接上测试代码了:

static ThreadLocal<String> threadLocal = new ThreadLocal<>();static InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();public static void main(String[] args) {threadLocal.set("abc");new Thread(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"====="+threadLocal.get());}},"thread1").start();inheritableThreadLocal.set("zhangsan");new Thread(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"====="+inheritableThreadLocal.get());}},"thread2").start();}

通过以上代码可以看出,thread1输出的是null, thread2输出的是zhangsan。

 

其实现原理也很简单。

InheritableThreadLocal重写了ThreadLocal的三个方法:
childValue,getMap,createMap。

源码如下:

public class InheritableThreadLocal<T> extends ThreadLocal<T> {protected T childValue(T parentValue) {return parentValue;}ThreadLocalMap getMap(Thread t) {return t.inheritableThreadLocals;}void createMap(Thread t, T firstValue) {t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);}}

 

当主线程调用  inheritableThreadLocal.set("zhangsan");

之后,调用的实际上是ThreadLocal的set方法,源码如下:

public void set(T value) {Thread t = Thread.currentThread();ThreadLocalMap map = getMap(t);if (map != null)map.set(this, value);elsecreateMap(t, value);}

可以看到set方法会先getMap,get不到就会createMap。主线程第一次调用getMap的时候,主线程对象里面的

inheritableThreadLocals引用默认指向的是null,所以第一次set的时候会执行createMap,因为实例化对象是inheritableThreadLocal对象,所以实际调用的也是他自己的createMap方法。

其实主线程里的set就做了一个事,就是对当前线程里面的inheritableThreadLocal变量进行实例化。

然后主线程里new Thread进行创建子线程的时候,这个时候会执行Thread的init方法,源码如下:

public Thread(Runnable target, String name) {init(null, target, name, 0);
}private void init(ThreadGroup g, Runnable target, String name,long stackSize) {init(g, target, name, stackSize, null, true);
}private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc,boolean inheritThreadLocals) {if (name == null) {throw new NullPointerException("name cannot be null");}this.name = name;Thread parent = currentThread();SecurityManager security = System.getSecurityManager();if (g == null) {/* Determine if it's an applet or not *//* If there is a security manager, ask the security managerwhat to do. */if (security != null) {g = security.getThreadGroup();}/* If the security doesn't have a strong opinion of the matteruse the parent thread group. */if (g == null) {g = parent.getThreadGroup();}}/* checkAccess regardless of whether or not threadgroup isexplicitly passed in. */g.checkAccess();/** Do we have the required permissions?*/if (security != null) {if (isCCLOverridden(getClass())) {security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);}}g.addUnstarted();this.group = g;this.daemon = parent.isDaemon();this.priority = parent.getPriority();if (security == null || isCCLOverridden(parent.getClass()))this.contextClassLoader = parent.getContextClassLoader();elsethis.contextClassLoader = parent.contextClassLoader;this.inheritedAccessControlContext =acc != null ? acc : AccessController.getContext();this.target = target;setPriority(priority);if (inheritThreadLocals && parent.inheritableThreadLocals != null)this.inheritableThreadLocals =ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);/* Stash the specified stack size in case the VM cares */this.stackSize = stackSize;/* Set thread ID */tid = nextThreadID();}

在init方法里面有一段代码

这里的parent是针对要创建的子线程而言的,实际是  Thread parent = currentThread();  ,在这里就是主线程本身。

调用了ThreadLocal的createInheritedMap方法,源码如下:

static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {return new ThreadLocalMap(parentMap);}private ThreadLocalMap(ThreadLocalMap parentMap) {Entry[] parentTable = parentMap.table;int len = parentTable.length;setThreshold(len);table = new Entry[len];for (int j = 0; j < len; j++) {Entry e = parentTable[j];if (e != null) {@SuppressWarnings("unchecked")ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();if (key != null) {Object value = key.childValue(e.value);Entry c = new Entry(key, value);int h = key.threadLocalHashCode & (len - 1);while (table[h] != null)h = nextIndex(h, len);table[h] = c;size++;}}}}

ThreadLocalMap是ThreadLocal的内部静态类。在ThreadLocalMap的构造函数中可以看出,这个是private的,其内部有一段代码是  Object value = key.childValue(e.value);  这个key就是ThreadLocal对象,在本示例中,就是inheritableThreadLocal对象,

也就是说调用了调用了inheritableThreadLocal的childValue方法进行获取到值,然后创建entry对象,放到map树里。

至此inheritableThreadLocal重写的三个方法都已经被调用了。

我们可以通过重写InheritableThreadLocal的childValue来改变get方法获取的值。

示例代码如下:

public class TestThreadLocal {static InheritableThreadLocal<String> inheritableThreadLocal1 = new MyThreadLocal<>    ("wocaolai");public static void main(String[] args) {inheritableThreadLocal1.set("zhangsan");new Thread(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"====="+inheritableThreadLocal1.get());}},"thread3").start();}static class MyThreadLocal<T>  extends InheritableThreadLocal<T> {public T myvalue;protected T childValue(T parentValue) {return myvalue;}public MyThreadLocal(T myvalue) {this.myvalue = myvalue;}}}

输出的结果是

而不是张三了。

这篇关于java.lang.InheritableThreadLocal的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java线程池核心参数原理及使用指南

《Java线程池核心参数原理及使用指南》本文详细介绍了Java线程池的基本概念、核心类、核心参数、工作原理、常见类型以及最佳实践,通过理解每个参数的含义和工作原理,可以更好地配置线程池,提高系统性能,... 目录一、线程池概述1.1 什么是线程池1.2 线程池的优势二、线程池核心类三、ThreadPoolE

Springboot请求和响应相关注解及使用场景分析

《Springboot请求和响应相关注解及使用场景分析》本文介绍了SpringBoot中用于处理HTTP请求和构建HTTP响应的常用注解,包括@RequestMapping、@RequestParam... 目录1. 请求处理注解@RequestMapping@GetMapping, @PostMappin

Java调用DeepSeek API的8个高频坑与解决方法

《Java调用DeepSeekAPI的8个高频坑与解决方法》现在大模型开发特别火,DeepSeek因为中文理解好、反应快、还便宜,不少Java开发者都用它,本文整理了最常踩的8个坑,希望对... 目录引言一、坑 1:Token 过期未处理,鉴权异常引发服务中断问题本质典型错误代码解决方案:实现 Token

SpringBoot整合AOP及使用案例实战

《SpringBoot整合AOP及使用案例实战》本文详细介绍了SpringAOP中的切入点表达式,重点讲解了execution表达式的语法和用法,通过案例实战,展示了AOP的基本使用、结合自定义注解以... 目录一、 引入依赖二、切入点表达式详解三、案例实战1. AOP基本使用2. AOP结合自定义注解3.

Java实现字符串大小写转换的常用方法

《Java实现字符串大小写转换的常用方法》在Java中,字符串大小写转换是文本处理的核心操作之一,Java提供了多种灵活的方式来实现大小写转换,适用于不同场景和需求,本文将全面解析大小写转换的各种方法... 目录前言核心转换方法1.String类的基础方法2. 考虑区域设置的转换3. 字符级别的转换高级转换

SpringBoot简单整合ElasticSearch实践

《SpringBoot简单整合ElasticSearch实践》Elasticsearch支持结构化和非结构化数据检索,通过索引创建和倒排索引文档,提高搜索效率,它基于Lucene封装,分为索引库、类型... 目录一:ElasticSearch支持对结构化和非结构化的数据进行检索二:ES的核心概念Index:

Java方法重载与重写之同名方法的双面魔法(最新整理)

《Java方法重载与重写之同名方法的双面魔法(最新整理)》文章介绍了Java中的方法重载Overloading和方法重写Overriding的区别联系,方法重载是指在同一个类中,允许存在多个方法名相同... 目录Java方法重载与重写:同名方法的双面魔法方法重载(Overloading):同门师兄弟的不同绝

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Java数组动态扩容的实现示例

《Java数组动态扩容的实现示例》本文主要介绍了Java数组动态扩容的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1 问题2 方法3 结语1 问题实现动态的给数组添加元素效果,实现对数组扩容,原始数组使用静态分配

Java中ArrayList与顺序表示例详解

《Java中ArrayList与顺序表示例详解》顺序表是在计算机内存中以数组的形式保存的线性表,是指用一组地址连续的存储单元依次存储数据元素的线性结构,:本文主要介绍Java中ArrayList与... 目录前言一、Java集合框架核心接口与分类ArrayList二、顺序表数据结构中的顺序表三、常用代码手动