当前位置:网站首页>面试官:ThreadLocal使用场景有哪些?内存泄露问题如何避免?
面试官:ThreadLocal使用场景有哪些?内存泄露问题如何避免?
2022-07-28 13:49:00 【InfoQ】
ThreadLocal使用场景有哪些?
ThreadLocal.ThreadLocalMap threadLocals = null;ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;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;}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内存泄露问题如何避免?

- ThreadLocal 不是用于解决共享变量的问题的,也不是为了协调线程同步而存在,而是为了方便每个线程处理自己的状态而引入的一个机制。这点至关重要。
- 每个Thread内部都有一个ThreadLocal.ThreadLocalMap类型的成员变量,该成员变量用来存储实际的ThreadLocal变量副本。
- ThreadLocal并不是为线程保存对象的副本,它仅仅只起到一个索引的作用。它主要是为每一个线程隔离一个类的实例,这个实例的作用范围仅限于线程内部。
边栏推荐
- 如何在 Core Data 中进行批量操作
- 开源项目丨Taier1.2版本发布,新增工作流、租户绑定简化等多项功能
- 3种方法解轮转数组
- Node file operation
- [ecmascript6] iterator and generator
- 软件测试工程师的职业规划
- 2022 melting welding and thermal cutting examination questions and online simulation examination
- Collaborative office tools: Online whiteboard is in its infancy, and online design has become a red sea
- 成为绿色数据中心新样板,东莞华为云数据中心是怎样炼成的?
- Foundation of deep learning ---- GNN spectral domain and airspace (continuous improvement, update and accumulation)
猜你喜欢

Minitest -- applet automation testing framework

2022高处安装、维护、拆除考试题库及在线模拟考试
![[ecmascript6] other new interface features](/img/da/377f93d83b6722bf250d270e4eea28.png)
[ecmascript6] other new interface features
C # 7 methods to obtain the current path

Leetcode 0142. circular linked list II

超好用的手机录屏软件推荐

ScottPlot入门教程:获取和显示鼠标处的数值

围绕新市民金融聚焦差异化产品设计、智能技术提效及素养教育
![[Tanabata] Tanabata lonely little frog research edition? The final chapter of Tanabata Festival!](/img/0b/4fc583a3dd4794b0c2b0d64d905be7.png)
[Tanabata] Tanabata lonely little frog research edition? The final chapter of Tanabata Festival!

bgp实验
随机推荐
[线程安全问题] 多线程到底可能会带来哪些风险?
文件批量重命名工具Bulk Rename Utility
JS instantiation method
C语言库函数getchar()怎么使用
MeterSphere--开源持续测试平台
[ecmascript6] modularization
HCIP第十一天
天气这么热太阳能发电不得起飞喽啊?喽啊个头……
C语言中浮点数据类型(你学废了吗)
HCIP第十天
树莓派基础 | 总结记录树莓派学习过程中的一些操作
Thoughts on the construction of some enterprise data platforms
软件测试的发展与定义
Forage QR code -- online QR code generator
[ecmascript6] class
Excel VBA 开发过程中遇到的一些问题,解决方案,持续更新
Floating point data type in C language (did you learn to waste it)
超好用的手机录屏软件推荐
2022 safety officer-a certificate operation certificate examination question bank simulated examination platform operation
Thesis study -- masked generative disintegration