ThreadLocal (二):什么时候使用 InheritableThreadLocal
一、ThreadLocal 在父子线程传递的问题
public class InheritableThreadLocalDemo { // 全局变量
// static ThreadLocal<String> threadLocal = new ThreadLocal<>();
static ThreadLocal<String> threadLocal = new InheritableThreadLocal<>(); public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
InheritableThreadLocalDemo.threadLocal.set("superWorld");
new Service().call();
}
}).start();
}
} class Service {
public void call() {
System.out.println("Service:" + Thread.currentThread().getName() + " : " + InheritableThreadLocalDemo.threadLocal.get());
//new Dao().call();
new Thread(new Runnable() {
@Override
public void run() {
new Dao().call();
}
}).start();
}
} class Dao {
public void call() {
System.out.println("Dao:" + Thread.currentThread().getName() + " : " + InheritableThreadLocalDemo.threadLocal.get());
} }
二、InheritableThreadLocal 和 ThreadLocal 的区别
1. InheritableThreadLocal 实现
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
/**
* Computes the child's initial value for this inheritable thread-local
* variable as a function of the parent's value at the time the child
* thread is created. This method is called from within the parent
* thread before the child is started.
* <p>
* This method merely returns its input argument, and should be overridden
* if a different behavior is desired.
*
* @param parentValue the parent thread's value
* @return the child thread's initial value
*/
protected T childValue(T parentValue) {
return parentValue;
} /**
* Get the map associated with a ThreadLocal.
*
* @param t the current thread
*/
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
} /**
* Create the map associated with a ThreadLocal.
*
* @param t the current thread
* @param firstValue value for the initial entry of the table.
*/
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
2. ThreadLocal 的getMap、createMap实现
/**
* 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;
} /**
* 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);
}
通过上面的代码我们可以看到InheritableThreadLocal 重写了childValue, getMap,createMap三个方法,
当我们往里面set值的时候,值保存到了inheritableThreadLocals里面,而不是之前的threadLocals。
三、问题:为什么当创建子线程时,可以获取到上个线程里的threadLocal中的值呢?
原因就是在新创建线程的时候,会把之前线程的inheritableThreadLocals赋值给新线程的inheritableThreadLocals,通过这种方式实现了数据的传递。
代码关键点:
1. Thread#init
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
2. 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++;
}
}
}
}
ThreadLocal (二):什么时候使用 InheritableThreadLocal的更多相关文章
- 理解ThreadLocal(二)
首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的.各 ...
- 彻底理解ThreadLocal二
首先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的.各 ...
- 深入理解ThreadLocal(二)
3 InheritableThreadLocal的使用 通过上面的分析知道通过ThreadLocal保存的值是线程隔离的.其实在Thread对象中,还有一个ThreadLocal.ThreadLoca ...
- 【并发编程】ThreadLocal的兄弟InheritableThreadLocal
本博客系列是学习并发编程过程中的记录总结.由于文章比较多,写的时间也比较散,所以我整理了个目录贴(传送门),方便查阅. 并发编程系列博客传送门 引子 public class InheritableT ...
- java多线程系类:JUC线程池:03之线程池原理(二)(转)
概要 在前面一章"Java多线程系列--"JUC线程池"02之 线程池原理(一)"中介绍了线程池的数据结构,本章会通过分析线程池的源码,对线程池进行说明.内容包 ...
- Java多线程系列--“JUC线程池”03之 线程池原理(二)
概要 在前面一章"Java多线程系列--“JUC线程池”02之 线程池原理(一)"中介绍了线程池的数据结构,本章会通过分析线程池的源码,对线程池进行说明.内容包括:线程池示例参考代 ...
- 【Java】深入理解ThreadLocal
一.前言 要理解ThreadLocal,首先必须理解线程安全.线程可以看做是一个具有一定独立功能的处理过程,它是比进程更细度的单位.当程序以单线程运行的时候,我们不需要考虑线程安全.然而当一个进程中包 ...
- ThreadLocal源码分析-黄金分割数的使用
前提 最近接触到的一个项目要兼容新老系统,最终采用了ThreadLocal(实际上用的是InheritableThreadLocal)用于在子线程获取父线程中共享的变量.问题是解决了,但是后来发现对T ...
- java中threadlocal的理解
[TOC] #java中threadlocal的理解##一.threadlocal的生命周期和ThreadLocalMap的生命周期可以吧TreadLocal看做是一个map来使用,只不过这个map是 ...
随机推荐
- 查看电脑CPU核心数的方法
查看电脑CPU核心数的方法: 方法一: 同时按下[Ctrl+Shift+Esc]组合快捷键打开任务管理器: 点击[性能]就可以看出是几核CPU了: 方法二: 在计算机图标上面点击右键,选择“管理”: ...
- 符合BME风格的弹窗\菜单\表格\文件上传控件
1.弹窗 2.菜单 3.表格 4.文件上传控件 笔记补充......
- 脱星摘帽刺激 ST板块表现出众
年报及业绩预告不断公布,在脱星摘帽.资产重组等一系列利好的刺激下,ST板表现出众.随着上市公司2015年财报披露的推进,*ST公司的命运也将浮出水面,近日多家有望“摘帽”的公司大多都走出了不错的行情, ...
- 服务器上使用matplotlib.pyplot绘图
在linux服务器端执行python脚本,有时候需要画图,但是linux没有GUI界面,因此需要在导入matplotlib.pyplot库之前先执行 import matplotlib as mpl ...
- 28. Search a 2D Matrix 【easy】
28. Search a 2D Matrix [easy] Write an efficient algorithm that searches for a value in an mx n matr ...
- LeetCode406. Queue Reconstruction by Height Add to List
Description Suppose you have a random list of people standing in a queue. Each person is described b ...
- D. Powerful array 离线+莫队算法 给定n个数,m次查询;每次查询[l,r]的权值; 权值计算方法:区间某个数x的个数cnt,那么贡献为cnt*cnt*x; 所有贡献和即为该区间的值;
D. Powerful array time limit per test seconds memory limit per test megabytes input standard input o ...
- vmware workstation 9.0.2安装教程
现在为您分享最新的VMware Workstation 9.0正式版(VMware Workstation 9.0.0 Build 812388)的下载,同时附上注册机或者注册激活码. 下载地址: ...
- Spring MVC文本框
以下示例显示如何使用Spring Web MVC框架在表单中使用文本框.首先使用Eclipse IDE来创建一个Web工程,按照以下步骤使用Spring Web Framework开发基于动态表单的W ...
- python 设计模式之单例模式
单例模式就是防止每个请求到来,都需要在内存里创建一个实例,再通过该实例执行指定的方法. 如果并发量大的话,内存里就会存在非常多功能上一模一样的对象.存在这些对象肯定会消耗内存,对于这些功能相同的对象可 ...