当前位置:网站首页>ThreadLocal summary (to be continued)
ThreadLocal summary (to be continued)
2022-07-25 22:19:00 【Swarford】
ThreadLocal
1. Java Memory model :
- Java All variables are stored in main memory
- Each thread has its own working memory , It stores the copy of variables used by the thread ( This copy is a copy of this variable in main memory )
- All operations of a thread on a shared variable must be performed in its own working memory , Can't read and write directly in main memory , After the thread modifies the variables, it should refresh them into the main memory ;
- Variables in the working memory of other threads cannot be accessed directly between different threads , The transfer of variable values between threads needs to pass through Main memory To complete .
Threads 1 Changes to shared variables , To be threaded 2 See in time , It has to go through the following 2 A process :
① Put the working memory 1 The shared variables updated in are refreshed to main memory
② Update the value of the latest shared variable in main memory to working memory 2 in
2. background
When multiple threads write to a variable, it is easy to cause thread safety problems , General users need additional synchronization measures to ensure thread safety when accessing shared variables ;
ThreadLocal It is a way to avoid thread insecurity in multi-threaded access in addition to locking ;
When we create a variable , If each thread accesses it All the variables accessed are the thread's own variables , In this way, there will be no thread safety problems .( Ensure thread safety by data isolation )
3. summary
ThreadLocal Provide an exclusive copy of variables for each thread , Each thread can change its own copy independently , It doesn't conflict with copies of other threads ;
If you create ⼀ individual ThreadLocal Variable , Then each thread accessing this variable will have a local copy of this variable ;
You can make ⽤ get() and set() ⽅ Method to get the default value or change its value to the value of the copy saved by the current thread , This avoids thread safety issues ;
example :
ThreadLocal The data of is isolated , Each thread can get a copy of the variable , Threads 2 Still got it null !
4. structure
JDK8 Before : key yes Thread, from Threadlocal To maintain the ThreadlocalMap 
JDK8 The benefits of changing the structure :
1.Thread As Key, When there are many threads Entry It's going to be a lot , and ThreadLocal As Key,Entry The number will be reduced a lot ;key Less hash conflicts can be avoided
2. When Thread At the time of destruction ,ThreadLocalMap It will be destroyed with it , Reduce memory overhead ; Early stage ThreadLocalMap from ThreadLocal maintain , Thread termination does not destroy ThreadLocalMap;
JDK8 Middle structure : key yes threadLocal object , from Thread Thread to maintain threadLocalMap

Structure description :
Every Thread Maintain a ThreadLocalMap,
Key yes Threadlocal object ,value Namely Threadlocal Of set Method stored value ( Copies of variables );
For different threads , Have their own different ThreadLocalMap, So we can isolate the data copies ;
5. set() 、get()、remove() Method source code
5.1 set()
1. Get the current thread object first ;
2. Gets the name of the thread object threadLocals attribute , That is to say threadLocalMap;
3. If map Existence will be the current threadLocal Object as key, The value passed in as value Pass in map; If map If it is empty, a map



5.2 get()
1. Get current Thread Thread object ;
2. Get threaded threadLocals namely threadLocalMap;
3. When map There is , With the current threadLocal The object is key, call map.getEntry How to get Entry Entity , if Entry If the entity is not empty, take out Entry In the question value;
4.① If map non-existent or ② Not with the current threadLocal Object associated Entry call setInitiavalue() Set initialization method :
Judge map, If empty, create map;
If map If it is not empty, the current ThreadLocal Object as key, and value Deposit in map


5.3 remove()
1. Get the current thread object ;
2. Get threaded threadLocals namely threadLocalMap;
3. If map If it is not empty, it will overflow the current threadLocal Object associated Entry
6. Memory leak problem
ThreadLocalMap Chinese envoy ⽤ Of key by ThreadLocal Of Weak reference ,⽽ value yes Strong citation . therefore , If
ThreadLocal Not forced by the outside ⽤ Under the circumstances , When it comes to recycling ,key It's going to be cleaned up ,⽽ value It won't be cleaned up ;
such ⼀ Come on , ThreadLocalMap Will appear in key by null Of Entry, If we don't do anything ,value forever ⽆ Dharma quilt GC Recycling , At this time, it may produce ⽣ Memory leak .
ThreadLocalMap This situation has been considered in the implementation , In tune ⽤ set() 、 get() 、 remove() Method time , Will clean up key by null The record of .
Use up ThreadLocal After the method It's better to call... Manually remove() Method ;
边栏推荐
- Wechat card issuing applet source code - automatic card issuing applet source code - with flow main function
- 什么是类加载?类加载的过程?
- H5 lucky scratch lottery free official account + direct operation
- SQL中in的用法 DQL 查询
- Win10 set up a flutter environment to step on the pit diary
- The automation testing post spent 20K recruiting, but in the end, there was no suitable one. Both fresh students are better than them
- internship:普通常用的工具类编写
- D3.js learning
- Acwing 866. determining prime numbers by trial division
- SQL基本语句 DQL select与提取 DML插入删除
猜你喜欢

Randomly generate 10 (range 1~100) integers, save them to the array, and print the array in reverse order. And find the average value, the maximum value and the subscript of the maximum value, and fin

The technical aspects of ByteDance are all over, but the result is still brushed. Ask HR why...

『Skywalking』. Net core fast access distributed link tracking platform

MySQL - subquery - column subquery (multi row subquery)

这次龙蜥展区玩的新花样,看看是谁的 DNA 动了?

聚名十年,说出你的故事,百万豪礼等你拿

字节跳动技术面都过了,结果还是被刷了,问HR原因竟是。。。

H5幸运刮刮乐抽奖 免公众号+直运营

kubernetes之VictoriaMetrics单节点

Advanced database · how to add random data for data that are not in all user data - Dragonfly Q system users without avatars how to add avatar data - elegant grass technology KIR
随机推荐
jenkins+SVN配置
3dslicer import cone beam CT image
Common source code for ArcGIS development
What is class loading? Class loading process?
win10搭建flutter环境踩坑日记
Three ways to allocate disk space
微信发卡小程序源码-自动发卡小程序源码-带流量主功能
Wechat official account application development (I)
arcgis开发常用源码
SQL基本语句 DQL select与提取 DML插入删除
After three years of software testing at Tencent, I was ruthlessly dismissed in July, trying to wake up my brother who was paddling
[dinner talk] those things that seem to be for the sake of the company but are actually incomprehensible (2: soft quality "eye edge" during interview)
突破性思维在测试工作中的应用
mysql: error while loading shared libraries: libncurses.so. 5: cannot open shared object file: No suc
Advanced database · how to add random data for data that are not in all user data - Dragonfly Q system users without avatars how to add avatar data - elegant grass technology KIR
Usage of in in SQL DQL query
4day
QML module not found
SQL中in的用法 DQL 查询
How to implement an app application to limit users' time use?