InheritableThreadLocal原理
转载:https://github.com/pzxwhc/MineKnowContainer/issues/20
介绍 InheritableThreadLocal 之前,假设对 ThreadLocal 已经有了一定的理解,比如基本概念,原理,如果没有,可以参考:前面两篇博文
这里再复习下 ThreadLocal 的原理,因为会对 InheritableThreadLocal 的理解 有重大的帮助:
- 每个线程都有一个 ThreadLocalMap 类型的 threadLocals 属性。
- ThreadLocalMap 类相当于一个Map,key 是 ThreadLocal 本身,value 就是我们的值。
- 当我们通过
threadLocal.set(new Integer(123));
,我们就会在这个线程中的 threadLocals 属性中放入一个键值对,key 是 这个 threadLocal.set(new Integer(123)); 的 threadlocal,value 就是值。 - 当我们通过
threadlocal.get()
方法的时候,首先会根据这个线程得到这个线程的 threadLocals 属性,然后由于这个属性放的是键值对,我们就可以根据键 threadlocal 拿到值。 注意,这时候这个键 threadlocal 和 我们 set 方法的时候的那个键 threadlocal 是一样的,所以我们能够拿到相同的值。
Ps:如果这个原理没搞清楚,那么下文估计有比较难理解,所以建议完完全全搞懂这个原理。
InheritableThreadLocal 概念
从上面的介绍我们可以知道,我们其实是根据 Thread.currentThread(),拿到该线程的 threadlocals,从而进一步得到我们之前预先 set 好的值。那么如果我们新开一个线程,这个时候,由于 Thread.currentThread() 已经变了,从而导致获得的 threadlocals 不一样,我们之前并没有在这个新的线程的 threadlocals 中放入值,那么我就再通过 threadlocal.get()方法 是不可能拿到值的。例如如下代码:
public class Test {
public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
public static void main(String args[]){
threadLocal.set(new Integer(123));
Thread thread = new MyThread();
thread.start();
System.out.println("main = " + threadLocal.get());
}
static class MyThread extends Thread{
@Override
public void run(){
System.out.println("MyThread = " + threadLocal.get());
}
}
}
输出是:
main = 123
MyThread = null
那么这个时候怎么解决? _InheritableThreadLocal 就可以解决这个问题。_ 先看一个官方对它的介绍:
* This class extends <tt>ThreadLocal</tt> to provide inheritance of values
* from parent thread to child thread: when a child thread is created, the
* child receives initial values for all inheritable thread-local variables
* for which the parent has values. Normally the child's values will be
* identical to the parent's; however, the child's value can be made an
* arbitrary function of the parent's by overriding the <tt>childValue</tt>
* method in this class.
也就是说,我们把上面的
public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
改成
public static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<Integer>();
再运行,就会有结果:
main = 123
MyThread = 123
也就是子线程或者说新开的线程拿到了该值。_那么,这个究竟是怎么实现的呢,key 都变了,为什么还可以拿到呢?_
InheritableThreadLocal 原理
我们可以首先可以浏览下 InheritableThreadLocal 类中有什么东西:
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);
}
}
其实就是重写了3个方法。
首先,当我们调用 get 方法的时候,由于子类没有重写,所以我们调用了父类的 get 方法:
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();
}
这里会有一个Thread.currentThread()
, getMap(t)
方法,所以就会得到这个线程 threadlocals。 但是,由于子类 InheritableThreadLocal 重写了 getMap()方法,再看上述代码,我们可以看到:
_其实不是得到 threadlocals,而是得到 inheritableThreadLocals。_ inheritableThreadLocals 之前一直没提及过,其实它也是 Thread 类的一个 ThreadLocalMap 类型的 属性,如下 Thread 类的部分代码:
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
那么,这里看 InheritableThreadLocal 重写的方法,感觉 inheritableThreadLocals 和 threadLocals 几乎是一模一样的作用,只是换了个名字而且,那么究竟 为什么在新的 线程中 通过 threadlocal.get()
方法还能得到值呢?
这时候要注意 childValue 方法,我们可以看下它的官方说明:
* 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.
这个时候,你明白了,是不是在 创建线程的时候做了手脚,做了一些值的传递,或者这里利用上了 inheritableThreadLocals 之类的。
其实,是的:
- _关键在于
Thread thread = new MyThread();
_ - _关键在于
Thread thread = new MyThread();
_ - _关键在于
Thread thread = new MyThread();
_
这不是一个简简单单的 new 操作。当我们 new 一个 线程的时候:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
然后:
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
init(g, target, name, stackSize, null);
}
然后:
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
......
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
......
}
这时候有一句 'ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);' ,然后
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++;
}
}
}
}
当我们创建一个新的线程的时候X,X线程就会有 ThreadLocalMap 类型的 inheritableThreadLocals ,因为它是 Thread 类的一个属性。
然后
先得到当前线程存储的这些值,例如 Entry[] parentTable = parentMap.table;
。再通过一个 for 循环,不断的把当前线程的这些值复制到我们新创建的线程X 的inheritableThreadLocals 中。就这样,就ok了。
那么这样会有一个什么结果呢?
结果就是我们创建的新线程X 的inheritableThreadLocals 变量中已经有了值了。那么我在新的线程X中调用threadlocal.get()
方法,首先会得到新线程X 的 inheritableThreadLocals,然后,再根据threadlocal.get()
中的 threadlocal,就能够得到这个值。
_这样就避免了 新线程中得到的 threadlocals 没有东西。之前就是因为没有东西,所以才拿不到值。_
所以说 整个 InheritableThreadLocal 的实现原理就是这样的。
总结
- 首先要理解 为什么 在 新线程中得不到值,是因为**我们其实是根据 Thread.currentThread(),拿到该线程的 threadlocals,从而进一步得到我们之前预先 set 好的值。那么如果我们新开一个线程,这个时候,由于 Thread.currentThread() 已经变了,从而导致获得的 threadlocals 不一样,我们之前并没有在这个新的线程的 threadlocals 中放入值,那么我就再通过 threadlocal.get()方法 是不可能拿到值的。**
- 那么解决办法就是 我们在新线程中,要把父线程的 threadlocals 的值 给复制到 新线程中的 threadlocals 中来。这样,我们在新线程中得到的 threadlocals 才会有东西,再通过
threadlocal.get()
中的 threadlocal,就会得到值。
InheritableThreadLocal原理的更多相关文章
- ThreadLoacl,InheritableThreadLocal,原理,以及配合线程池使用的一些坑
虽然使用AOP可以获取方法签名,但是如果要获取方法中计算得出的数据,那么就得使用ThreadLocal,如果还涉及父线程,那么可以选择InheritableThreadLocal. 注意:理解一些原理 ...
- ThreadLocal及InheritableThreadLocal的原理剖析
我们知道,线程的不安全问题,主要是由于多线程并发读取一个变量而引起的,那么有没有一种办法可以让一个变量是线程独有的呢,这样不就可以解决线程安全问题了么.其实JDK已经为我们提供了ThreadLocal ...
- 关于Spring事务的原理,以及在事务内开启线程,连接池耗尽问题.
主要以结果为导向解释Spring 事务原理,连接池的消耗,以及事务内开启事务线程要注意的问题. Spring 事务原理这里不多说,网上一搜一大堆,也就是基于AOP配合ThreadLocal实现. 这里 ...
- TransmittableThreadLocal 解决 线程池线程复用 无法复制 InheritableThreadLocal 的问题.
ThreadLoacl,InheritableThreadLocal,原理,以及配合线程池使用的一些坑 TransmittableThreadLocal 原理 之前为了能让InheritableThr ...
- 【并发编程】ThreadLocal的兄弟InheritableThreadLocal
本博客系列是学习并发编程过程中的记录总结.由于文章比较多,写的时间也比较散,所以我整理了个目录贴(传送门),方便查阅. 并发编程系列博客传送门 引子 public class InheritableT ...
- ThreadLocal源码解析
主要用途 1)设计线程安全的类 2)存储无需共享的线程信息 设计思路 ThreadLocalMap原理 1)对象存储位置-->当前线程的ThreadLocalMap ThreadLocalMap ...
- ThreadLocal源码解读
1. 背景 ThreadLocal源码解读,网上面早已经泛滥了,大多比较浅,甚至有的连基本原理都说的很有问题,包括百度搜索出来的第一篇高访问量博文,说ThreadLocal内部有个map,键为线程对象 ...
- InheritableThreadLocal类原理简介使用 父子线程传递数据详解 多线程中篇(十八)
上一篇文章中对ThreadLocal进行了详尽的介绍,另外还有一个类: InheritableThreadLocal 他是ThreadLocal的子类,那么这个类又有什么作用呢? 测试代码 p ...
- ThreadLocal系列(二)-InheritableThreadLocal的使用及原理解析
ThreadLocal系列之InheritableThreadLocal的使用及原理解析(源码基于java8) 上一篇:ThreadLocal系列(一)-ThreadLocal的使用及原理解析 下一篇 ...
随机推荐
- FAQ: C++中定义类的对象:用new和不用new有何区别?
C++用new创建对象和不用new创建对象的区别解析 作者: 字体:[增加 减小] 类型:转载 时间:2013-07-26 我要评论 在C++用new创建对象和不用new创建对象是有区别的,不知你是否 ...
- using 名称空间指定一个别名
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- JavaOOP QuickHit项目分析
项目需求:游戏等级6级,随机字符串每级长度不同.每升一级减少比较次数,但是字符串长度相应增加!每级总分数不同,如果游戏中途输入错误则游戏退出!玩家每次在规定时间内输入字符串的同时,打印出游戏难度等级. ...
- 13---Net基础加强
更新中,敬请期待............ 作业-复习 程序集1 程序集2 反射1 反射2 反射3 反射4-记事本插件1 反射5-记事本插件2
- java post请求
package com.jfbank.loan.intf.util; import java.io.IOException;import java.util.ArrayList;import java ...
- 夺命雷公狗---DEDECMS----7dedecms目录结构
我们dedecms的目录结构其实只需要一张图即可明了了,如下图所示:
- linux强制umount设备的方法
假如挂载时使用了:mount /dev/sda1 /mnt/sda1 #查找占用设备的pid fuser -m /mnt/sda1 #假如此时得到的pid为12345 kill -9 12345 um ...
- selenium启动PhantomJS错误
from selenium import webdriverbrowser = webdriver.PhantomJS(executable_path="D:\PhantomJS\phant ...
- html5 图片热点area,map的用法
今天看了一个html5在图片上面创建热点的标签,所谓图片热点就是给你一张图片然后你可以设置点击图片不同的位置进入不同的链接!如果下面是一张图片的话,里面在长方形.圆形.三角形区域都可以进入其他网页! ...
- java hashMap缓存简单实现
直接上代码,干货: import java.util.HashMap; import java.util.Map; /** * map缓存 * @author ming * * @param < ...