当前位置:网站首页>Simple understanding of ThreadLocal
Simple understanding of ThreadLocal
2022-07-02 12:14:00 【huan_ one thousand nine hundred and ninety-three】
List of articles
One 、 background
Recently someone asked me ThreadLocal
How to make the values in each thread isolated , Write an article here to briefly record .
Two 、ThreadLocal Problem solved
- The data belongs to the thread
Thread
Oneself , Other threads cannot affect it .( We need to pay attention to : Need to call ThreadLocal Of remove Method ) - There is no thread safety issue .( because
ThreadLocal
A variable of type can only be accessed by its own thread , So this is true .)
such as :
After the user logs in successfully , Need to put Login user information
Save up , So that you can use... Anywhere in the system , Then you can use ThreadLocal
To achieve . for example :Spring Security
Medium ThreadLocalSecurityContextHolderStrategy
class .
3、 ... and 、 How to create a ThreadLocal example
private static final ThreadLocal<String> USER_NAME = new ThreadLocal<>();
ThreadLocal For example, it is recommended to use private static final
To modify .
Four 、ThreadLocal How to achieve thread variable isolation
1、 understand 3 Classes
ThreadLocal
: This class provides a simpleset
,get
,remove
Method , Used for setting up , Get or remove Bound to the value in the thread local variable .ThreadLocalMap
: This is ThreadLocal A class defined in , It can be simply understood as a Map, But its key yes WeakReference Weak reference type , So when the value is not referenced elsewhere , In case of garbage collection , This map Ofkey
Will be automatically recycled , However, its value will not be automatically recycled .static class Entry extends WeakReference<ThreadLocal<?>> { Object value; Entry(ThreadLocal<?> k, Object v) { // key Weak reference super(k); // Value strong reference value = v; } }
Thread
: This is the thread class , There is a in this classthreadLocals
Variable , The specific type isThreadLocal.ThreadLocalMap
.
2、 look down set How are methods implemented
public void set(T value) {
// Get the current thread
Thread t = Thread.currentThread();
// Get the... Bound to the thread itself ThreadLocalMap, This ThreadLocalMap It's from Thread Class `threadLocals` Variable
ThreadLocalMap map = getMap(t);
if (map != null) {
// towards map Set the value of ,key by ThreadLocal Instance of object .
map.set(this, value);
} else {
// If map non-existent , Then create .
createMap(t, value);
}
}
Through the code above , We know : When we turn to ThreadLocal Set a value in the , It will go through the following steps :
- Get the current thread
Thread
- Gets the current thread's
ThreadLocalMap
object . - towards
ThreadLocalMap
Set the value of ,key byThreadLocal
object , The value is a specific value .
3、 have a look get How to achieve
public T get() {
// Get the current thread
Thread t = Thread.currentThread();
// Get the binding of the thread itself ThreadLocalMap object
ThreadLocalMap map = getMap(t);
if (map != null) {
// this yes ThreadLocal object , obtain Map Medium Entry object
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
// Get specific values
T result = (T)e.value;
return result;
}
}
// Set initial value
return setInitialValue();
}
From above get and set The way to know , Through to ThreadLocal Object to set or get a value , In fact, it is the final operation to Thread Object threadLocals Field , And this field is Thread Self , Therefore, isolation is achieved .
5、 ... and 、ThreadLocalMap Medium hash How the conflict is handled
1、ThreadLocal Object's hash What is the value
private final int threadLocalHashCode = nextHashCode();
// The ThreadLocal Of the object itself hash code value
private final int threadLocalHashCode = nextHashCode();
// from 0 Start
private static AtomicInteger nextHashCode = new AtomicInteger();
// Increment a fixed value each time
private static final int HASH_INCREMENT = 0x61c88647;
// hash code Value calculation
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
From the code above, you can ,ThreadLocal
Class after instantiation , its hash code value (threadLocalHashCode)
It's fixed , Even if ThreadLocal
Called set
Method , Other values are set , its hash code value
It won't change .
This field threadLocalHashCode
by ThreadLocal
Object's hash value , stay ThreadLocalMap
This is needed in hash value .
2、 solve hash Conflict
ThreadLocalMap
solve hash The solution to conflict is simple . Is through linear detection . If there is a conflict , Just look for the available position behind the array . See the picture above for details . The demonstration is A and B 2 individual ThreadLocal object , Then there was a conflict ,A and B The location of existence is in that place .
6、 ... and 、ThreadLocal Memory leak
ThreadLocal Why is there a memory leak ?
This is because ThreadLocalMap
Medium key
yes WeakReference
type , That is, weak reference types , Data with weak reference type has no external strong reference type , In the event of a gc
When , Will be automatically recycled . Be careful :
Now it's key
It's recycled , however value
There is no recycling . So in ThreadLocalMap
Medium Entry[]
There may be key
yes null
, however value
Is an object of concrete value , So there is a memory leak .
Fix memory leaks :
When we're done ThreadLocal
After the object , Need to call... At the right time ThreadLocal#remove()
Method . Otherwise, we have to wait Thread
Auto exit to clear , If the thread pool is used ,Thread
Reuse , The opportunity to clear is even more difficult .
边栏推荐
- MSI announced that its motherboard products will cancel all paper accessories
- On data preprocessing in sklearn
- Sub thread get request
- 计算二叉树的最大路径和
- 怎样写一篇赏心悦目的英文数学论文
- CPU指令集介绍
- [QT] Qt development environment installation (QT version 5.14.2 | QT download | QT installation)
- Day12 control flow if switch while do While guessing numbers game
- 输入一个三位的数字,输出它的个位数,十位数、百位数。
- 小程序链接生成
猜你喜欢
Read the Flink source code and join Alibaba cloud Flink group..
Lekao: contents of the provisions on the responsibility of units for fire safety in the fire protection law
CDH存在隐患 : 该角色的进程使用的交换内存为xx兆字节。警告阈值:200字节
SVO2系列之深度濾波DepthFilter
Deep understanding of NN in pytorch Embedding
The blink code based on Arduino and esp8266 runs successfully (including error analysis)
YYGH-BUG-04
Map和Set
基于Arduino和ESP8266的连接手机热点实验(成功)
深入理解PyTorch中的nn.Embedding
随机推荐
Leetcode122 买卖股票的最佳时机 II
Leetcode922 sort array by parity II
Multiply LCA (nearest common ancestor)
arcgis js 4.x 地图中加入图片
kubenetes中port、targetPort、nodePort、containerPort的区别与联系
Le tutoriel F - String le plus facile à comprendre de l'histoire.
怎样写一篇赏心悦目的英文数学论文
Leetcode14 longest public prefix
Sort---
Pytorch builds LSTM to realize clothing classification (fashionmnist)
CDH存在隐患 : 该角色的进程使用的交换内存为xx兆字节。警告阈值:200字节
Natural language processing series (I) -- RNN Foundation
排序---
记录一下MySql update会锁定哪些范围的数据
刷题---二叉树--2
Test shift left and right
自然语言处理系列(一)——RNN基础
机械臂速成小指南(七):机械臂位姿的描述方法
Jenkins voucher management
测试左移和右移