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,ThreadLocalClass 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:ThreadLocalClass defines a static inner classThreadLocalMapEach Thread has oneThreadLocalMapType 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 internallythreadLocalstheInstance members, its type isThreadLocal.ThreadLocalMap.
Thread : ThreadLocal.ThreadLocalMap threadLocals
Copy the code
  • ThreadLocalIt’s not a container by itself, and the value that we access is actually stored inThreadLocalMap,ThreadLocalJust as aTheadLocalMapThe key is ultimately stored inEntry[] tableIn 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-valuesWeakReferenceA subclass of
static class Entry extends WeakReference<ThreadLocal<? >>Copy the code

referenceThreadLocalThe object is reclaimed becauseThreadLocalMapholdThreadLocalEven without manual deletion,ThreadLocalIt gets recycled. Value next timeThreadLocalMapcallset,get,removeWill 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.