当前位置:网站首页>Interviewer: what are the usage scenarios of ThreadLocal? How to avoid memory leakage?
Interviewer: what are the usage scenarios of ThreadLocal? How to avoid memory leakage?
2022-07-28 18:48:00 【nuzzzzz】
ThreadLocal What are the use scenarios ?

Thread There are two variables in the class threadLocals and inheritableThreadLocals, Both ThreadLocal Inner class ThreadLocalMap Variable of type , We look inside ThreadLocalMap It can be found that it is actually similar to a HashMap. By default , These two variables in each thread are null:
ThreadLocal.ThreadLocalMap threadLocals = null;ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;Only when the thread first calls ThreadLocal Of set perhaps get Methods before they are created .
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();} ThreadLocalMap getMap(Thread t) { return t.threadLocals;}besides , The local variables of each thread are not stored in ThreadLocal In the example , Instead, it is placed on the of the calling thread ThreadLocals In variables . in other words ,ThreadLocal Local variables of type are stored in specific thread space , It itself is equivalent to a carrier for loading local variables , adopt set Methods will value Added to the calling thread threadLocals in , When the calling thread calls get Methods can be learned from its threadLocals Take variables out of . If the calling thread never terminates , Then this local variable will always be stored in his threadLocals in , So when you don't use local variables, you need to call remove Methods will threadLocals Delete unused local variables , Prevent memory leaks .
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value);}public void remove() { ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null) m.remove(this);}ThreadLocal How to avoid memory leakage ?
Every Thread There is one.
ThreadLocal.ThreadLocalMap Of map, The map Of key by ThreadLocal example , It's a weak reference , We know that weak citation is good for GC Recycling . When ThreadLocal Of key == null when ,GC It's going to reclaim that space , however value But it doesn't have to be recycled , Because he's still with Current Thread There is a strong reference relationship , as follows

Because of this strong reference relationship , It can lead to value It can't be recycled . If the thread object is not destroyed, the strong reference relationship will always exist , There will be a memory leak . So as long as this thread object can be used in time GC Recycling , There will be no memory leaks . If you run into a thread pool , That's even worse . So how to avoid this problem ? I mentioned earlier , stay ThreadLocalMap Medium setEntry()、getEntry(), If you encounter key == null The situation of , Would be right value Set to null. Of course, we can also display the call ThreadLocal Of remove() Methods to deal with . Let's do it again ThreadLocal Make a brief summary :
- ThreadLocal Not to solve the problem of shared variables , It doesn't exist to coordinate thread synchronization , It is a mechanism introduced to facilitate each thread to handle its own state . This is crucial .
- Every Thread There's one inside ThreadLocal.ThreadLocalMap A member variable of type , This member variable is used to store the actual ThreadLocal Copies of variables .
- ThreadLocal Instead of saving a copy of the object for the thread , It only serves as an index . It mainly isolates an instance of a class for each thread , The scope of this instance is only within the thread .
边栏推荐
- jvm四种引用类型
- 2022.7.26 constructor, interview: the role of new, deep copy and shallow copy
- 1.2、队列
- MySQL日期函数
- 视频融合云服务EasyCVR平台白名单功能如何使用?
- MYSQL入门与进阶(三)
- Ue5 gas learning notes 1.8 game special effects (gameplaycue)
- LeetCode_343_整数拆分
- Six countries in Europe and the United States launched an express line product to optimize the "end-to-end" performance service on the 5th
- Noise of creative coding
猜你喜欢

C# 之 观察者模式实例 -- 订牛奶
![[actual combat] realize page distortion correction with OpenCV](/img/7b/7e25bde34a9d5463af3dd40599c80e.png)
[actual combat] realize page distortion correction with OpenCV

MYSQL入门与进阶(二)

2022-07-27 study notes of group 4 self-cultivation class (every day)

Introduction and advanced level of MySQL (6)

Tencent Tang Daosheng: open source is a new mode of production and collaboration in the era of industrial Internet

NDK series (5): from introduction to practice, JNI explodes the liver and explains everything in detail!

Redis缓存雪崩、穿透、击穿,布隆过滤器,分布式锁详解

EasyCVR新版本级联时,下级平台向上传递层级目录显示不全的原因分析

冒泡排序和相关视频
随机推荐
UE5 GAS 学习笔记 1.5 Gameplay Effects游戏效果
Ue5 gas learning notes 1.2 game Tags
Golang并发模型之
MySQL index usage and optimization
2022-07-27 第四小组 修身课 学习笔记(every day)
ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法
1.2 queue
LeetCode_ 1137_ Nth teponacci number
实验楼----PHP大法
MongoDB初始化
UE5 GAS 学习笔记0.2配置插件
.net WCF wf4.5 state machine, bookmark and persistence
Zero knowledge proof: zkp with DDH assumption
1.1、稀疏数组
Redis缓存雪崩、穿透、击穿,布隆过滤器,分布式锁详解
Go语言系列之日志库zap
408 review strategy (strengthening stage)
UE5 GAS 学习笔记 1.6 技能Gameplay Ability
It is said that software testing is the worst in the IT industry. Is that so?
UE5 GAS 学习笔记 1.3属性Attribute