ThreadLocal principle
1. What is ThreadLocal
ThreadLocal provides thread local variables. The difference between these variables and ordinary variables is that each thread accessing this variable (through its get or set method) has its own independently initialized copy of the variable.
ThreadLocal instances are usually private static fields (such as user ID or transaction ID) of classes that want to associate the state to a thread.
(
Voice over: this passage expresses three meanings
)
For example, in the following example, this class generates a unique ID for each thread. The ID of a thread is the first time it calls ThreadID Specified by the get () method.
2. Main operations of ThreadLocal
3. Read the source code
3.1. Set method
You can see that the bottom layer of threadlocalmap is an array, and the element type in the array is entry type
The set operation is to the ThreadLocal of the current thread Set the value in threadlocals, a member variable of threadlocalmap type. Key is this and value is the value we specify
Note that this passed here represents the ThreadLocal type variable (or object)
That is, each thread maintains a ThreadLocal Threadlocalmap type object, and the set operation actually takes the ThreadLocal variable as the key and the value specified by us as the value. Finally, the key value pair is encapsulated into an entry object and placed in the ThreadLocal of the thread Threadlocalmap object. Each ThreadLocal variable is ThreadLocal in the thread An entry in the threadlocalmap object. Since each ThreadLocal variable corresponds to ThreadLocal If an element in threadlocalmap, you can read, write, delete these elements.
3.2. Get method
The get () method is from the ThreadLocal Get the value corresponding to the corresponding ThreadLocal variable from the threadlocalmap object
Similarly, the remove () method clears this value
If it is represented graphically, it is roughly as follows:
Or something like this:
4. ThreadLocal usage scenario
Finally, we owe everything to threadlocalmap