当前位置:网站首页>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 .
边栏推荐
- Summer Challenge [FFH] JS custom component: DIY a keyboard that can be used at any time! (I)
- Ue5 gas learning notes 1.4 attribute set
- UE5 GAS 学习笔记 1.5 Gameplay Effects游戏效果
- 【实战】用OpenCV实现页面扭曲矫正
- mysql 索引使用与优化
- UE5 GAS 学习笔记 1.2游戏标签
- [actual combat] realize page distortion correction with OpenCV
- How does Xiaobai learn software testing with zero foundation?
- Ue5 gas learning notes 0.1 case Preview
- Redis缓存雪崩、穿透、击穿,布隆过滤器,分布式锁详解
猜你喜欢

高德地图实现自定义小蓝点 自定义点标记 绘制多边形/圆形区域 根据地图的移动显示或者隐藏自定义点标记的相关实现

MYSQL入门与进阶(一)

ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法

Golang并发模型之

Introduction and advanced MySQL (4)

112. 使用自开发的代理服务器解决 SAP UI5 FileUploader 上传文件时遇到的跨域访问错误

kotlin:Nothing

LeetCode_63_不同路径Ⅱ

Zero knowledge proof: zkp with DDH assumption

What if you don't understand the difference between modularity, componentization and plug-in?
随机推荐
数字化转型中的DevOps——弹性合作
What is the future of software testing?
NPM cannot recognize the "NPM" item as the name of a cmdlet, function, script file, or runnable program. Please check the spelling of the name. If the path is included, make sure the path is correct,
[actual combat] realize page distortion correction with OpenCV
视频融合云服务EasyCVR平台白名单功能如何使用?
MySQL日期函数
Summer Challenge [FFH] JS custom component: DIY a keyboard that can be used at any time! (I)
全新升级!《云原生架构白皮书 2022 版》重磅发布
UE5 GAS 学习笔记 1.8 游戏特效(GameplayCue)
1.2 queue
数字经济时代的开源数据库创新 | 2022开放原子全球开源峰会数据库分论坛圆满召开
行业落地呈现新进展 | 2022开放原子全球开源峰会OpenAtom OpenHarmony分论坛圆满召开
1.1、稀疏数组
UE5 GAS 学习笔记 1.10 预测(Prediction)
1.1. Sparse array
记录自己在厦门两年来的面试经历--完结篇
Introduction and advanced level of MySQL (8)
三分钟了解快来新媒体
[GXYCTF2019]StrongestMind
UE5 GAS 学习笔记 1.6 技能Gameplay Ability