The issue of object preservation has always been a concern for us when doing program research. The same operation also exists in ThreadLocal, we can store and retrieve objects. This requires a certain understanding of ThreadLocal and the use of its set method. Below we will explain the complete operation steps of ThreadLocal storage and acquisition, and share the specific content with you.
1. ThreadLocal’s set method
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
Through the set method of ThreadLocal, we can see that in the <k, v> structure of ThreadLocalMap, the key stores the ThreadLocal itself, and the value is the actual stored value. In other words, a copy of the variable copied by the current ThreadLocal is stored in the ThreadLocalMap. .
2. ThreadLocal itself does not store values. In use, ThreadLocal is used as a key to obtain the value from ThreadLocalMap. This can also be seen from the get method of ThreadLocal:
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }
The above is the object storage and acquisition of java ThreadLocal. The key is to master the use of set. If you are not proficient enough in this method, you must practice more after class.