当前位置:网站首页>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 .
边栏推荐
- Meta Q2财报:营收首次下滑,Metaverse将与苹果竞争
- 408 review strategy (strengthening stage)
- Mingde biology: no products of the company have been listed in the WHO recommended list
- Is it really realistic that people who have not been exposed to software testing can take up their posts after two months of training?
- UE5 GAS 学习笔记 1.5 Gameplay Effects游戏效果
- EasyNLP中文文图生成模型带你秒变艺术家
- kotlin:Nothing
- Devops in digital transformation -- flexible cooperation
- What is the employment prospect of software testing?
- Multithreading and high concurrency -- source code analysis AQS principle
猜你喜欢
随机推荐
数字经济时代的开源数据库创新 | 2022开放原子全球开源峰会数据库分论坛圆满召开
Is the training institution of software testing reliable
MYSQL入门与进阶(一)
SQL Server stuff and for XML path
Go语言系列之日志库zap
LeetCode_ 343_ integer partition
从 SRE 看 DevOps 建设
2022.7.26 构造函数,面试:new的作用、深拷贝和浅拷贝
haproxy实现代理配置
Ue5 gas learning notes 0.1 case Preview
408 review strategy (strengthening stage)
EasyCVR设备离线后无法再次上线该如何解决?
UE5 GAS 学习笔记8.0参考资料
MYSQL入门与进阶(十)
redis持久化之RDB和AOF的区别
LVS manual
Zero knowledge proof: zkp with DDH assumption
MongoDB初始化
UE5 GAS 学习笔记 1.10 预测(Prediction)
Meta Q2财报:营收首次下滑,Metaverse将与苹果竞争









