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是 ...
随机推荐
- python--web项目
zope:一个容器项目Plone:一个基于zope的工作流和内容管理项目trac:一个项目管理(任务指派.bug追踪项目,可以和subversion集成)moinmoin:一个强力的weiki系统
- Centos开机自己主动挂载windows中的ntfs磁盘
装了windows和centos双系统后,发如今centos中无法进入windows中的磁盘,更不要说查看磁盘里的文件了! 原来默认情况下.centos不支持Widows NTFS硬盘分区读写,要想把 ...
- jQuery中事件绑定
一.前言 最近在做项目中要用到jQuery来绑定事件,首先想到的是$(selector).事件名();这样绑定事件的方式,这种方式对事件进行绑定其实也就是bind()方法,但当选择器匹配的元素过多,$ ...
- Intellj IDEA14.0.2启动异常之3分钟修复
今天是周一,刚到公司启动心爱的IDEA,,突然启动到一半,就抛异常了,直接弹窗,报例如以下的异常: java.lang.RuntimeException: com.intellij.ide.plugi ...
- JsCal( JS Calendar)
http://www.dynarch.com/projects/calendar Doc: http://www.dynarch.com/jscal/ This is the documentatio ...
- There's no Qt version assigned to this project for platform Win32. Please use the 'change Qt version' feature and choose a valid Qt version for this platform.
这个是用在vs2015时爆出的问题. 解决方法是: 1.鼠标放置在解决方案中的工程名处,用鼠标右键点击(右击). 2.选择Qt Project Settings,在弹出的对话框中的version栏处填 ...
- C++ Primer(第五版)读书笔记 & 习题解答 --- Chapter 2
Chapter 2.1 1. 数据类型决定了程序中数据和操作的意义. 2. C++定义了一套基本数据类型,其中包括算术类型和一个名为void的特殊类型.算术类型包含了字符.整型.布尔值以及浮点数.vo ...
- PHP基础之Autoload
PHP的自动加载autoload机制很重要,这里做2个小练习 原创文章,转载请注明:http://www.cnblogs.com/phpgcs 文件结构如下,2种方式实现自动加载 1,自定义函数 2, ...
- ansible学习之--安装Svn
1.安装svn 机器 Ubuntu SMP Thu Jan 15 20:21:55 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux 使用 sudo apt-get in ...
- centos7.4 install ss-qt5
一切都是为了FQ,哦,说错了,是***-- 参考官网安装指南 1.新建repo文件 vim /etc//yum.repos.d/shadowssocks.repo 2.在文件中输入以下内容: [lib ...