Understanding ThreadLocal -- a map key, threadlocalmap
Purpose: When ThreadLocal is used to maintain a variable for a multi-threaded object, threadLocal allocates an independent copy of the variable for each thread that uses the variable. Interface Method:
Protected T initialValue () // initialize data. The call method is delayed. It is executed only once when the thread calls get or set for the first time. By default, null is returned. Public T get () // get the variable public void set (T value) of the current thread // set the variable public void remove () of the current thread // Delete the variable of the current thread
It is relatively simple to view the source code of ThreadLocal. First look at the get method:
public T get() { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) return (T)e.value; } return setInitialValue();}
ThreadLocalMap getMap(Thread t) { return t.threadLocals;}
If data is retrieved from ThreadLocalMap and no data is returned, the default value is set and the result is returned (So initialValue is a delayed call ). ThreadLocalMap is the attribute of the current thread, and the map key is the current ThreadLocal object. Therefore, get is actually a method to search for value based on the key. It only stores the map and hides it in the current Thread.
Example:
The initialization is as follows: three threadLocal objects.
For example, the first data is stored in threadLocals of Thread @ 1 in map [ThreadLocalMap @ 432. The key is this, that is, ThreadLocal @ 428, that is, the firstNum in Figure 1.
For example, the second data is stored in threadLocals of Thread @ 1 in map [ThreadLocalMap @ 432. The key is this, that is, ThreadLocal @ 430, that is, secondNum of figure 1.
For example, the third data is stored in threadLocals of Thread @ 1 in map [ThreadLocalMap @ 432. The key is this, that is, ThreadLocal @ 429, that is, the thirdNum in Figure 1.
Complete.
--------------------------------------
It is important to clarify things, and I am trying to do something like this. Please kindly advise.