当前位置:网站首页>Source code series of authentic children -inheritablethreadlocal (line by line source code takes you to analyze the author's ideas)
Source code series of authentic children -inheritablethreadlocal (line by line source code takes you to analyze the author's ideas)
2022-07-01 19:48:00 【Sky flaw】
Java edition :8u261.
I wrote it before, right ThreadLocal Source code analysis of the article , If you are interested, you can check 《 More serious children learn source code series -ThreadLocal( Line by line source code takes you to analyze the author's ideas )》.
InheritableThreadLocal yes ThreadLocal Subclasses of , According to the previous analysis ,ThreadLocal Variables can only be shared within the same thread , and InheritableThreadLocal Not only can variables be shared in the same thread , Moreover, variables can be shared between parent and child threads . For example, in the parent thread a Created a child thread in b, So in a Used in thread InheritableThreadLocal Packaged variables , In the child thread b It can also be obtained in . But it should be noted that :InheritableThreadLocal and ThreadLocal equally , The value of a variable cannot still be shared in a peer thread . also InheritableThreadLocal Only the father can pass on the son , You can't pass from son to father ( At the same time, it is not always possible to pass from father to son , Data transfer occurs only at the beginning of initialization , You'll see that later ).
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);
}
}
The above is InheritableThreadLocal All the source code of , It can be seen that it just overwrites ThreadLocal Just three ways . And in the getMap and createMap Method inheritableThreadLocals This attribute , So what exactly does this attribute do ? In fact, it is threadLocals Same property , It's all in Thread Properties in a class :
public class Thread implements Runnable {
//...
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
/*
* InheritableThreadLocal values pertaining to this thread. This map is
* maintained by the InheritableThreadLocal class.
*/
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
//...
}
It's because of inheritableThreadLocals This attribute , You can let the child thread access the local variables in the parent thread .
When creating a thread , Will be called to Thread Class init Method :
/**
* Thread:
*/
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
//...
Thread parent = currentThread();
//...
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
/*
In the parent thread inheritableThreadLocals The data is initialized to a new ThreadLocalMap in ,
And assign it to the child thread inheritableThreadLocals
*/
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
//...
}
Other irrelevant logic is omitted here , Just take a look at inheritableThreadLocals The initialization process , Further follow up the second 17 Line code :
/**
* ThreadLocal:
*/
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
//parentMap Is the data in the parent thread
return new ThreadLocalMap(parentMap);
}
/**
* The... In the parent thread inheritableThreadLocals Copy to a new ThreadLocalMap in
* Personally, I think it will directly parentMap It should also be possible to go back , But here's a reconstruction
* ThreadLocalMap It feels like it's for cleaning up , take Entry by null Clean up the hash slot
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
// Set the of child threads threshold
setThreshold(len);
// Initializes the of the child thread table( Because it is called here when the sub thread is created , Therefore, there is no need to judge whether it has been initialized , This must be uninitialized )
table = new Entry[len];
// Traverse the parent thread table
for (int j = 0; j < len; j++) {
// Get the Entry
Entry e = parentTable[j];
if (e != null) {
// Get... In the current slot Entry Stored in the ThreadLocal
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
// This is going to call InheritableThreadLocal Overwritten childValue Method , That is to return to e.value In itself
Object value = key.childValue(e.value);
// Building a new Entry
Entry c = new Entry(key, value);
// Get the location of the hash slot
int h = key.threadLocalHashCode & (len - 1);
// Find the position to be inserted by linear detection
while (table[h] != null)
h = nextIndex(h, len);
// insert data
table[h] = c;
// Count +1
size++;
}
}
}
}
/**
* InheritableThreadLocal:
* The first 32 Line code :
*/
protected T childValue(T parentValue) {
return parentValue;
}
The complete process is as follows :
- First, the parent thread calls set or get When the method is used , Would call InheritableThreadLocal Overwritten getMap Method returns inheritableThreadLocals, But because it is not initialized , So the override will be called createMap Method to create ThreadLocalMap, And assign it to inheritableThreadLocals. So the parent thread inheritableThreadLocals The attribute is not null 了 ;
- Then the parent thread will call set Method to the parent thread inheritableThreadLocals Attribute table Assign a value to an array ;
- Then when you create a child thread , Would call Thread Class init Methods ThreadLocal.createInheritedMap Method . Parent thread inheritableThreadLocals The data in the property is initialized to a new ThreadLocalMap in , And assign values to child threads at the same time inheritableThreadLocals. The of such a sub thread inheritableThreadLocals Property has the data in the parent thread ;
- Finally, the sub thread calls get Method, you can get the data in the parent thread . But here's the thing : After the execution of the sub thread , The parent thread calls get The method still gets the from the previous parent thread inheritableThreadLocals, It's not that the child thread will change into it ThreadLocalMap. That is, the data of the child thread will not be passed to the parent thread , The child thread will synchronize the data in the parent thread only at the beginning of initialization .
Originality is not easy. , Without permission , Do not reprint , Version will investigate
边栏推荐
- How to add transactions in JDBC
- 118. Yanghui triangle
- Bao, what if the O & M 100+ server is a headache? Use Xingyun housekeeper!
- 118. 杨辉三角
- Interview questions for audio and video positions in Dachang -- today's headline
- Uni app wechat applet one click login to obtain permission function
- 音频编解码基础知识
- GC垃圾回收
- 振弦采集模块测量振弦传感器的流程步骤
- 大厂音视频职位面试题目--今日头条
猜你喜欢
servlet知识点
Example explanation: move graph explorer to jupyterlab
[research materials] iResearch tide Watching: seven major trends in the clothing industry - Download attached
Process steps of vibrating wire acquisition module for measuring vibrating wire sensor
118. 杨辉三角
Wireshark packet analysis TCP, FTP
产品模块化设计的前世今生
118. Yanghui triangle
wireshark报文分析tcp,ftp
GB28181之SIP协议
随机推荐
js三元表达式复杂条件判断
【无标题】
Wechat applet navigator has a shadow after clicking. Remove the shadow effect of navigator
墨天轮沙龙 | 清华乔嘉林:Apache IoTDB,源于清华,建设开源生态之路
面试题 16.16. 部分排序-双指针法
Actual combat of flutter - fast implementation of audio and video call application
H264 encoding profile & level control
OpenCV视频质量诊断----视频遮挡诊断
微信小程序 navigator点击后有阴影 ,去掉navigator阴影效果
Image acquisition and playback of coaxpress high speed camera based on pxie interface
Opencv video quality detection -- sharpness detection
optaplanner学习笔记(一)案例Cloud balance
H264编码profile & level控制
Leetcode 1380 lucky numbers in matrix [array] the leetcode path of heroding
对象的创建
2022/6/8-2022/6/12
Botu V16 obtains the system time and converts it into a string
DTD modeling
一个程序员如何快速成长
Analysis of GetMessage underlying mechanism