当前位置:网站首页>ThreadLocal到底在干嘛?
ThreadLocal到底在干嘛?
2022-07-23 05:45:00 【wzf6667】
threadlocal使用
Treadlocal 简介
通常情况下,我们创建的变量是可以被任何一个线程访问并修改的。如果想实现每一个线程都有自己的专属本地变量该如何解决呢? JDK中提供的ThreadLocal类正是为了解决这样的问题。 ThreadLocal类主要解决的就是让每个线程绑定自己的值,可以将ThreadLocal类形象的比喻成存放数据的盒子,盒子中可以存储每个线程的私有数据。
如果你创建了一个ThreadLocal变量,那么访问这个变量的每个线程都会有这个变量的本地副本,这也是ThreadLocal变量名的由来。他们可以使用 get() 和 set() 方法来获取默认值或将其值更改为当前线程所存的副本的值,从而避免了线程安全问题。
就好比有一个公用的笔记本,谁都可以往上面写东西。但是有的人不满意了,他只想让笔记本上有自己的东西,相当于每个人都有一个笔记本
Treadlocal 原理
最简单的想法就是在Threadlocal里面建立一张线程安全的map表,thread作为key,set进去的值作为value,每个线程从里面找到自己的value。但是实际建表采用的是下面这种方法。
Thread里面有一个参数叫做threadlocals的变量,他是ThreadLocalMap类型的。ThreadLocalMap可以看成是一个线程安全的hashmap,是threadlocal的一个静态内部类。意思就是每个线程都有一个叫threadlocals的map,key是threadlocal,value你set进去的object。而threadlocal就相当于是threadlocalmap的一个封装。每次set和get值都是从本线程里的map找到key为threadlocal的value。
两种方法的比较
这样设计之后每个Map的Entry数量变小了:之前是Thread的数量,现在是ThreadLocal的数量,能提高性能;
当Thread销毁之后对应的ThreadLocalMap也就随之销毁了,能减少内存使用量。
把一张应该建在threadlocal里面大表分成好多的小表,放在了每个线程里。这些小表会随着线程的消亡而消亡。
ThreadLocal 内存泄露问题
ThreadLocalMap 中使用的 key 为 ThreadLocal 的弱引用,而 value 是强引用。所以,如果 ThreadLocal 没有被外部强引用的情况下,在垃圾回收的时候,key 会被清理掉,而 value 不会被清理掉。这样一来,ThreadLocalMap 中就会出现key为null的Entry。假如我们不做任何措施的话,value 永远无法被GC 回收,这个时候就可能会产生内存泄露。ThreadLocalMap实现中已经考虑了这种情况,在调用 set()、get()、remove() 方法的时候,会清理掉 key 为 null 的记录。使用完 ThreadLocal方法后 最好手动调用remove()方法
边栏推荐
- 常见的排序方法—选择排序
- 【Autosar 存储Stack NVM】
- 嵌入式从入门到精通(入土)——超详细知识点分享3
- 理解不能的锁们
- 【AUTOSAR CanDrive 1.学习CanDrive的功能和结构】
- 动态规划——“换硬币问题”
- Interpretation of the paper: "i4mc deep: intelligent prediction of N4 methylcytosine sites using deep learning methods with chemical properties"
- Upper and lower case letter conversion
- Prometheus
- Interpretation of the paper: "bert4bitter: a basic model for improving bitter peptide prediction based on transformer (BERT) bidirectional encoder representation"
猜你喜欢
![[physical layer of CAN bus] 1. Content sharing of can/canfd sampling points](/img/e4/0b709a6ed5e639a75e0506f6eac9fd.png)
[physical layer of CAN bus] 1. Content sharing of can/canfd sampling points

Questions and answers of basic principles of steel structure
Blog Building III: comment system selection

A comprehensive and detailed summary of the basic principles of steel structure

【Autosar 存储Stack NVM】

Steel structure review questions

Anonymous upper computer V7 waveform display

C语言小项目——学生成绩管理系统

Redis——基础概念

输入三角形边长,求面积
随机推荐
关于如何排查vpn服务器无法转发的问题
Embedded from entry to mastery (buried) - sharing of ultra detailed knowledge points 2
基于UDP的群聊聊天室
输入三角形边长,求面积
二叉树基础oj练习-
【AUTOSAR COM 3.信号的收发流程TX/RX】
Upper and lower case letter conversion
高电压技术复习资料
Redis——配置及应用
【AUTOSAR CanTP 1.学习UDS诊断的网络层协议】
Embedded from entry to mastery (buried) - sharing of ultra detailed knowledge points 1
冒泡排序,快速排序
【Autosar 存储Stack NVM】
视频编解码相关资料汇总
Prometheus Operator使用指南笔记
1、经济学十大原理
LVS负载均衡调度原理及配置方法
3.2daydayup draw inferences from one instance: three days of fishing and two days of net learning
钢结构基本原理试题及答案
APISIX的源码安装与使用