当前位置:网站首页>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 .
边栏推荐
- Chapter 10 project communication management
- String exercise summary 2
- Short video mall system, how does scroll view adapt to the remaining height of the page
- 04A interrupt configuration
- Online filing process
- What aspects should we start with in the feasibility analysis of dry goods?
- 故障安全移动面板KTP900F Mobile下载程序提示无法下载,目标设备正在运行或未处于传输模式的解决办法
- 关于自动控制原理资料更新
- How to extract dates from web pages?
- 嵌入式开发:技巧和窍门——干净地从引导加载程序跳转到应用程序代码
猜你喜欢

PostMan工具介绍及安装使用

NIO、BIO、AIO

In the multi network card environment, the service IP registered by Nacos is incorrect, resulting in inaccessible services

Ansible basic configuration

AQS源码分析
![leetcode:515. Find the maximum value in each tree row [brainless BFS]](/img/87/1926d783fb6f8d8439213d86b5da40.png)
leetcode:515. Find the maximum value in each tree row [brainless BFS]

Basic principles of spanning tree protocol

Can AI chat robots replace manual customer service?

华大04a工作模式/低功耗模式

AQS source code analysis
随机推荐
Chapter 10 project communication management
无心剑汉英双语诗003. 《书海》
AQS source code analysis
Idea global search replace shortcut key
What aspects should we start with in the feasibility analysis of dry goods?
Creating files, recursively creating directories
Technology inventory: past, present and future of Message Oriented Middleware
[Software Engineering] key points at the end of the period
揭秘B站,程序员穿女装敲代码,效率更高是真的吗?
The ktp900f mobile download program of the fail safe mobile panel prompts that the download cannot be performed, and the target device is running or not in the transmission mode
Industrial development status of virtual human
华大4A0GPIO设置
Yyds dry goods inventory junit5 learning II: assumptions class
60 divine vs Code plug-ins!!
NIO 零拷贝
虚拟人的产业发展现状
Description of software version selection of kt6368a Bluetooth dual-mode transparent chip
Resolving the conflict problem of the flutter Library
ThreadLocal内存泄漏问题
How to compare two or more distributions: a summary of methods from visualization to statistical testing