当前位置:网站首页>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 .
边栏推荐
- MYSQL入门与进阶(一)
- npm 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
- 112. 使用自开发的代理服务器解决 SAP UI5 FileUploader 上传文件时遇到的跨域访问错误
- MYSQL入门与进阶(二)
- 高德地图实现自定义小蓝点 自定义点标记 绘制多边形/圆形区域 根据地图的移动显示或者隐藏自定义点标记的相关实现
- Kotlin:Sealed class密封类详解
- UE5 GAS 学习笔记 1.6 技能Gameplay Ability
- Meta Q2财报:营收首次下滑,Metaverse将与苹果竞争
- MYSQL入门与进阶(十)
- MYSQL入门与进阶(三)
猜你喜欢

Gaode map realizes customized small blue dots, customized point markers, drawing polygon / circular areas, and displaying or hiding customized point markers according to the movement of the map

Experimental building - PHP Dafa

Ue5 gas learning notes 0.2 configuration plug-in

Introduction and advanced level of MySQL (10)

Zero knowledge proof: zkp with DDH assumption

Error 2003 (HY000) can't connect to MySQL server on 'localhost3306' (10061) solution

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

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

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

mysql 索引使用与优化
随机推荐
ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法
数字经济时代的开源数据库创新 | 2022开放原子全球开源峰会数据库分论坛圆满召开
APP为什么用JSON协议与服务端交互:序列化相关知识
Bubble sorting and Related videos
冒泡排序和相关视频
Ue5 gas learning notes 0.2 configuration plug-in
Introduction and advanced MySQL (4)
.net swagger
kotlin:out in
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,
112. 使用自开发的代理服务器解决 SAP UI5 FileUploader 上传文件时遇到的跨域访问错误
Noise of creative coding
1.1. Sparse array
视频融合云服务EasyCVR平台白名单功能如何使用?
It is said that software testing is the worst in the IT industry. Is that so?
2022.7.26 构造函数,面试:new的作用、深拷贝和浅拷贝
.net WCF wf4.5 state machine, bookmark and persistence
kotlin:out in
[actual combat] realize page distortion correction with OpenCV
Gateway入门