当前位置:网站首页>ThreadLocal memory leak
ThreadLocal memory leak
2022-06-24 22:33:00 【Nice2cu_ Code】
ThreadLocal principle
Before reading this article , You need to know Java The concept of medium strength, weakness and emptiness , Delivery address :Java Weak weak weak weak weak weak weak weak
List of articles
One 、 Introduce
- It can solve the data security problem of multithreading , take The current thread is associated with a data ( It can be a normal variable , It can be the object , It can also be an array , Collection etc. )
- Each thread can only access the data of this thread , Unable to manipulate data from other threads , The data of each thread is independent of each other
- ThreadLocal It defines
set、get、removeMethod , Used to relate / Take out / Remove data - every last ThreadLocal object , Can only be associated for the current thread One data , If you want to associate multiple data for the current thread , You need to use multiple ThreadLocal Object instances
Two 、 Quick start
public class ThreadLocalTest {
public static void main(String[] args) throws InterruptedException {
// establish ThreadLocal Object instances
final ThreadLocal<Integer> th = new ThreadLocal<Integer>();
//t1 Threads
new Thread(new Runnable() {
@Override
public void run() {
try {
th.set(100); //t1 Threads store data
System.out.println("t1 The value given by the thread :" + th.get());
Thread.sleep(2000); //t1 Thread sleep 2 second , During sleep t2 The thread will run
System.out.println("t1 The value obtained by the thread :"+th.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(1000);
//t2 Threads
new Thread(new Runnable() {
@Override
public void run() {
Integer ele = th.get(); //t2 Thread fetches data ( This is the case null, And t1 It doesn't matter )
System.out.println("t2 The value obtained by the thread :" + ele);
th.set(200); //t2 Thread assignment
System.out.println("t2 The value obtained after the thread assignment :"+th.get()); //t2 The thread gets the value from its own copy
}
}).start();
}
}
Running results :

3、 ... and 、ThreadLocal And synchronized The difference between
- The principle is different
- synchronized
- Only one piece of data was provided , Let different threads compete for lock access
- ThreadLocal
- Each thread is provided with its own data , So as to achieve simultaneous access without mutual interference
- synchronized
- Different emphasis
- synchronized
- Synchronization of accessing resources between multiple threads
- ThreadLocal
- In multithreading, the data between each thread Mutual isolation
- synchronized
Four 、ThreadLocal internal structure
Every
ThreadMaintain aThreadLocalMap, This Map OfkeyyesThreadLocalThe instance itself ,valueIs the real value to store
Icon

Map from Entry Key value pairs make up
When
ThreadAfter destruction , CorrespondingThreadLocalMapIt will be destroyed with it , Can reduce the use of memory
5、 ... and 、ThreadLocal Core method source code
1. set Method
Source code and corresponding Chinese Notes
/** * Parameter is Map Medium value value */ public void set(T value) { // Get the current thread object Thread t = Thread.currentThread(); // Gets the... Maintained in this thread object ThreadLocalMap object ThreadLocalMap map = getMap(t); // Judge map Whether there is if (map != null) // If it exists, call set Method ,this Indicates... In this thread TheadLocal example // establish Entry And the assignment map.set(this, value); else // If the current thread does not exist ThreadLocalMap object , Create Map createMap(t, value); } /** * The called getMap Method * @param Current thread * @return Corresponding to the maintenance of ThreadLocalMap */ ThreadLocalMap getMap(Thread t) { return t.threadLocals; } /** * The called createMap Method * @param Current thread * @param Store in Map The first of entry Value */ void createMap(Thread t, T firstValue) { //this yes ThreadLocal example t.threadLocals = new ThreadLocalMap(this, firstValue); }Code execution process
- First, get the current thread , And get one according to the current thread Map
- If you get Map Not empty , Set the parameter to Map in ( At present ThreadLocal As a reference to key), establish Entry And the assignment
- If Map It's empty , Then create for the thread Map, And set the initial value , The initial value is the parameter value
2. get Method
Source code and corresponding Chinese Notes
/** * Returns the value of the current thread Map Medium value value */ public T get() { // Get the current thread object Thread t = Thread.currentThread(); // Gets the... Maintained in this thread object ThreadLocalMap object ThreadLocalMap map = getMap(t); // If so map There is if (map != null) { // With the current ThreadLocal by key, call getEntry Get the corresponding Entry ThreadLocalMap.Entry e = map.getEntry(this); // If Entry Not empty , Return the corresponding value value if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } // There are two situations in which setInitialValue() Method // Case one : map non-existent , Indicates that this thread does not maintain ThreadLocalMap object // The second case : map There is , But not with the current ThreadLocal The associated entry return setInitialValue(); } /** * The called setInitialValue Method , establish Entry And return the corresponding value value , The default is null */ private T setInitialValue() { // call initialValue Get the initialization value // This method can be overridden by subclasses , If you don't override the default return null T value = initialValue(); // Get the current thread object Thread t = Thread.currentThread(); // Gets the... Maintained in this thread object ThreadLocalMap object ThreadLocalMap map = getMap(t); // Judge map Whether there is if (map != null) // If it exists, call map.set Set this entity entry map.set(this, value); else // 1. Current thread Thread non-existent ThreadLocalMap object // 2. Call createMap Conduct ThreadLocalMap Object initialization // 3. And will t( Current thread ) and value( The default is null) As the first entry Store in ThreadLocalMap in createMap(t, value); // Returns the set value value, The default is null return value; }Code execution process
- First, get the current thread , Get a from the current thread Map
- If you get Map Not empty , It's in Map China and Israel ThreadLocal As a reference to key stay Map Get the corresponding
Entry e - If e Not empty , Then return to
e.value - If Map Empty or e It's empty , Through
initialValue()Function to get the initial value value( The default is null), And then use ThreadLocal References to and value As firstKey and firstValue Create a new Map
summary : First get the... Of the current thread ThreadLocalMap Variable , If it exists, it returns the value , If it doesn't exist, create and return the initial value .
6、 ... and 、 Use of weak references
Entry The corresponding source code is as follows :
//Entry Inherited from a weak reference
static class Entry extends WeakReference<ThreadLocal<?>> {
// attribute value
Object value;
// Constructors
Entry(ThreadLocal<?> k, Object v) {
super(k); // The parent class creates a weak reference , Parameter is ThreadLocal object
value = v;
}
}
// The called parent method
public WeakReference(T referent) {
super(referent);
}
// The called parent method , The second parameter refers to queue delivery null value
Reference(T referent, ReferenceQueue<? super T> queue) {
this.referent = referent;
this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
}
Through the above source code , establish Entry A weak reference will be created when , And points to the of the current thread ThreadLocal object , As shown in the figure below :

1. Why use weak references ?
If Entry Medium key Use strong references to point to ThreadLocal object , When ThreadLocal example threadLocal = null; when , because ThreadLocal The object is still Entry Medium key Strong citation , therefore ThreadLocal Objects will not be garbage collected , There is a memory leak .
Memory leak : Objects will not be GC Recovered , But it takes up memory .
If you use weak references , When garbage is recycled ,ThreadLocal Object is recycled , Can solve ThreadLocal Object memory leak .
2. Whether memory leaks still exist after using weak references ?
When ThreadLocal After the object is recycled ,Entry Medium key by null, Can't get value Value , It can't be recycled , therefore value There is still a memory leak in the memory space pointed to , Therefore, it should be used remove() Method to this clause Entry Record deletion .
3. Thread pool return threads must be cleaned up Map
If the thread in the thread pool returns , Not cleaned up ThreadLocalMap, When this thread is used again , May lead to Map An error occurred in the data in , For example, discovery Map There is already a with the same name in key, No new values will be inserted .
边栏推荐
- 堆内存分配的并发问题
- YGG 近期游戏合作伙伴一览
- Publicity of the second batch of shortlisted enterprises! Annual Top100 smart network supplier selection
- 华大4A0GPIO设置
- Servlet details
- 故障安全移动面板KTP900F Mobile下载程序提示无法下载,目标设备正在运行或未处于传输模式的解决办法
- Genesis公链与美国一众加密投资者齐聚Consensus 2022
- 【软件工程】期末重点
- CA Zhouji - the first lesson in 2022 rust
- 无心剑汉英双语诗003. 《书海》
猜你喜欢

Chapter 10 project communication management

波卡生态发展不设限的奥义——多维解读平行链
![Find the maximum value in each tree row [extension of one of the hierarchical traversals]](/img/5b/81ff20b61c0719ceb6873e44878859.png)
Find the maximum value in each tree row [extension of one of the hierarchical traversals]

Uncover the secret of station B. is it true that programmers wear women's clothes and knock code more efficiently?
![leetcode:45. Jumping game II [classic greed]](/img/69/ac5ac8fe22dbb8ab719d09efda4a54.png)
leetcode:45. Jumping game II [classic greed]

Resolving the conflict problem of the flutter Library

How to extract dates from web pages?

Ansible basic configuration

VRRP skills topic

ansible基本配置
随机推荐
NIO多路复用之Selector的使用
CSRF and SSRF for web attacks
AQS源码分析
socket done
Certificate photo processing
Learning notes 23-- basic theory of multi-sensor information fusion (Part I)
Data communication and physical network
Concurrency of heap memory allocation
How does flutter use the online transcoding tool to convert JSON to model
How to extract dates from web pages?
进程的通信方式
envoy获取客户端真实IP
问题求解——嵌套列表
leetcode:55. 跳跃游戏【经典贪心】
Idea global search replace shortcut key
AQS source code analysis
Description of transparent transmission function before master and slave of kt6368a Bluetooth chip, 2.4G frequency hopping automatic connection
Docker installs MySQL 8.0. Detailed steps
Online filing process
代理模式详解