当前位置:网站首页>Simple understanding of ThreadLocal
Simple understanding of ThreadLocal
2022-07-03 06:08:00 【xuhss_ com】
High quality resource sharing
| Learning route guidance ( Click unlock ) | Knowledge orientation | Crowd positioning |
|---|---|---|
| 🧡 Python Actual wechat ordering applet 🧡 | Progressive class | This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system . |
| Python Quantitative trading practice | beginner | Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system |
Catalog * One 、 background
- Two 、ThreadLocal Problem solved
- 3、 ... and 、 How to create a ThreadLocal example
- Four 、ThreadLocal How to achieve thread variable isolation
- 5、 ... and 、ThreadLocalMap Medium hash How the conflict is handled
- 6、 ... and 、ThreadLocal Memory leak
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
ThreadOneself , 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
ThreadLocalA 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 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,removeMethod , 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 OfkeyWill be automatically recycled , However, its value will not be automatically recycled .
static class Entry extends WeakReference> {
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 classthreadLocalsVariable , 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
ThreadLocalMapobject . - towards
ThreadLocalMapSet the value of ,key byThreadLocalobject , 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 .
边栏推荐
- Exception when introducing redistemplate: noclassdeffounderror: com/fasterxml/jackson/core/jsonprocessingexception
- pytorch DataLoader实现miniBatch(未完成)
- Maximum likelihood estimation, divergence, cross entropy
- Migrate data from Amazon aurora to tidb
- Oauth2.0 - use database to store client information and authorization code
- Kubernetes notes (IX) kubernetes application encapsulation and expansion
- PMP笔记记录
- Bio, NiO, AIO details
- 理解 YOLOV1 第一篇 预测阶段
- Project summary --2 (basic use of jsup)
猜你喜欢

arcgis创建postgre企业级数据库
![[minesweeping of two-dimensional array application] | [simple version] [detailed steps + code]](/img/b0/aa5dce0bb60c50eea907de9e127d6c.jpg)
[minesweeping of two-dimensional array application] | [simple version] [detailed steps + code]

The most responsible command line beautification tutorial

Skywalking8.7 source code analysis (II): Custom agent, service loading, witness component version identification, transform workflow

GPS坐标转百度地图坐标的方法

Redhat7 system root user password cracking

Bernoulli distribution, binomial distribution and Poisson distribution, and the relationship between maximum likelihood (incomplete)

Oauth2.0 - explanation of simplified mode, password mode and client mode
![[teacher Zhao Yuqiang] index in mongodb (Part 2)](/img/a7/2140744ebad9f1dc0a609254cc618e.jpg)
[teacher Zhao Yuqiang] index in mongodb (Part 2)
![[Zhao Yuqiang] deploy kubernetes cluster with binary package](/img/cc/5509b62756dddc6e5d4facbc6a7c5f.jpg)
[Zhao Yuqiang] deploy kubernetes cluster with binary package
随机推荐
Using the ethtool command by example
从 Amazon Aurora 迁移数据到 TiDB
从小数据量 MySQL 迁移数据到 TiDB
Kubernetes notes (I) kubernetes cluster architecture
Analysis of Clickhouse mergetree principle
卷积神经网络CNN中的卷积操作详解
智牛股项目--05
PHP用ENV获取文件参数的时候拿到的是字符串
有意思的鼠标指针交互探究
Convolution operation in convolution neural network CNN
智牛股项目--04
Ext4 vs XFS -- which file system should you use
phpstudy设置项目可以由局域网的其他电脑可以访问
Kubernetes notes (10) kubernetes Monitoring & debugging
Intel's new GPU patent shows that its graphics card products will use MCM Packaging Technology
[teacher Zhao Yuqiang] use the catalog database of Oracle
Jackson: what if there is a lack of property- Jackson: What happens if a property is missing?
[teacher Zhao Yuqiang] MySQL high availability architecture: MHA
1. Somme des deux nombres
使用 Abp.Zero 搭建第三方登录模块(一):原理篇