当前位置:网站首页>ThreadLocal详解
ThreadLocal详解
2022-07-06 14:53:00 【菜鸟小窝】
一、ThreadLocal
1、说明
ThreadLocal 是一个线程局部变量。其实的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是Java中一种较为特殊的线程绑定机制,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。
2、使用方法
ThreadLocal<String> nameThreadLocal = new ThreadLocal<>();
nameThreadLocal.set(name);
nameThreadLocal.get();
3、Request 使用案例
在springMvc中单例controller中定义成员变量 request ,使用@autowired注入时,request就是使用ThreadLocal实现线程安全的。
- 在controller中注入的request是jdk动态代理对象,ObjectFactoryDelegatingInvocationHandler的实例.当我们调用成员域request的方法的时候其实是调用了objectFactory的getObject()对象的相关方法.这里的objectFactory是RequestObjectFactory.
- RequestObjectFactory的getObject其实是从RequestContextHolder的threadlocal中去取值的.
- 请求刚进入springmvc的dispatcherServlet的时候会把request相关对象设置到RequestContextHolder的threadlocal中去.
参考:在SpringMVC Controller中注入Request成员域 - abcwt112 - 博客园
4、参考
ThreadLocal详解
https://www.jianshu.com/p/3bb70ae81828
二、InheritableThreadLocal
1、说明
ThreadLocal设计之初就是为了绑定当前线程,如果希望当前线程的ThreadLocal能够被子线程使用,实现方式就会相当困难(需要用户自己在代码中传递)。在此背景下,InheritableThreadLocal应运而生。
2、原理
创建新的线程时,会调用以下的构造方法。
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
我们沿着构造方法中的init方法,可以找到这样一段代码。就是在这里创建的 inheritableThreadLocals 。
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
继续查看 createInheritedMap 方法,里面新建了一个 ThreadLocalMap 对象,其构造方法如下。
分析代码我们可知,在创建子线程时,会将父线程的 inheritableThreadLocals 复制到子线程的 inheritableThreadLocals 对象。
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
3、参考
InheritableThreadLocal详解
https://www.jianshu.com/p/94ba4a918ff5
三、ThreadLocal内存泄漏
https://blog.csdn.net/qq_25775675/article/details/105731434
边栏推荐
- Seata聚合 AT、TCC、SAGA 、 XA事务模式打造一站式的分布式事务解决方案
- 2021 geometry deep learning master Michael Bronstein long article analysis
- 【数字IC手撕代码】Verilog无毛刺时钟切换电路|题目|原理|设计|仿真
- 小程序系统更新提示,并强制小程序重启并使用新版本
- Oracle control file and log file management
- Hardware development notes (10): basic process of hardware development, making a USB to RS232 module (9): create ch340g/max232 package library sop-16 and associate principle primitive devices
- 新手程序员该不该背代码?
- Mysql database basic operations DML
- Data storage (1)
- OpenCV VideoCapture. Get() parameter details
猜你喜欢

2500个常用中文字符 + 130常用中英文字符

Aardio - 封装库时批量处理属性与回调函数的方法

Web APIs DOM 时间对象

Management background --2 Classification list
The SQL response is slow. What are your troubleshooting ideas?

硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件

Spatial domain and frequency domain image compression of images
Learn the principle of database kernel from Oracle log parsing

Memorabilia of domestic database in June 2022 - ink Sky Wheel

Crawler obtains real estate data
随机推荐
如何用程序确认当前系统的存储模式?
Unity3d minigame-unity-webgl-transform插件转换微信小游戏报错To use dlopen, you need to use Emscripten‘s...问题
二叉(搜索)树的最近公共祖先 ●●
Anaconda installs third-party packages
CCNA Cisco network EIGRP protocol
Unity3d Learning Notes 6 - GPU instantiation (1)
二分图判定
2022-07-05 使用tpcc对stonedb进行子查询测试
【数字IC手撕代码】Verilog无毛刺时钟切换电路|题目|原理|设计|仿真
The SQL response is slow. What are your troubleshooting ideas?
C # réalise la liaison des données du rapport Crystal et l'impression du Code à barres 4
Solve project cross domain problems
Self made j-flash burning tool -- QT calls jlinkarm DLL mode
Leetcode question brushing (XI) -- sequential questions brushing 51 to 55
Web APIs DOM 时间对象
Oracle control file and log file management
Report on technological progress and development prospects of solid oxide fuel cells in China (2022 Edition)
Inno Setup 打包及签名指南
软考高级(信息系统项目管理师)高频考点:项目质量管理
数据处理技巧(7):MATLAB 读取数字字符串混杂的文本文件txt中的数据