ThreadLocal
- Requirement: In multi-threading, each thread needs to have a variable of the same name, which can be accessed independently by different threads without affecting each other.
- Action: For the same variable,
ThreadLocal
Class can create a copy for each thread. In this way, the variable becomes a “local variable” for each thread, and access is not affected by each other, ensuring thread-safety (ThreadLocal is not intended to achieve mutually exclusive access to a variable). - Principle:
ThreadLocal
Class defines a static inner classThreadLocalMap
Each Thread has oneThreadLocalMap
Type variablethreadLocals
, which uses threadLocals to store copies of variables for each thread. ThreadLocals has an Entry array to find copies of variables for the corresponding thread based on the key-value thread object. - The cause of the memory leak has been found, and the culprit is Java TheadLocal
1. Use of ThreadLocal
Scene:
- When you need to store thread-private variables.
- When you need to implement thread-safe variables.
- When you need to reduce contention for thread resources.
The common usage methods are as follows:
// new
ThreadLocal<BigObject> threadLocal = new ThreadLocal<>();
/ / set
threadLocal.set(new BigObject());
/ / get
BigObject bo = threadLocal.get();
/ / remove delete
threadLocal.remove();
Copy the code
2. ThreadLocal data structures
- Each Thread is a Thread instance, and each Thread instance corresponds to a TheadLocalMap instance.
- It maintains one internally
threadLocals
theInstance members, its type isThreadLocal.ThreadLocalMap
.
Thread : ThreadLocal.ThreadLocalMap threadLocals
Copy the code
ThreadLocal
It’s not a container by itself, and the value that we access is actually stored inThreadLocalMap
,ThreadLocal
Just as aTheadLocalMap
The key is ultimately stored inEntry[] table
In the array.
ThreadLocalMap map = Thread.currentThread().threadLocals;
map.put(this,value);
map.get(this);
Copy the code
- Entry in TheadLocalMap is a pair of key-values
WeakReference
A subclass of
static class Entry extends WeakReference<ThreadLocal<? >>Copy the code
referenceThreadLocal
The object is reclaimed becauseThreadLocalMap
holdThreadLocal
Even without manual deletion,ThreadLocal
It gets recycled. Value next timeThreadLocalMap
callset
,get
,remove
Will be cleared.
3. Does ThreadLocal have memory leaks?
Since ThreadLocalMap has a lifetime as long as Thread, failure to manually remove the corresponding key would result in a memory leak, not weak references.
So how do you avoid memory leaks? Each time ThreadLocal is used, it is recommended to call its remove() method to clean up the data.