Thread ThreadLocal ThreadLocalMap relationship

1. There is a variable in the Thread class, which is of type ThreadLocalMap

2. This  ThreadLocalMap is responsible for storing all the ThreadLocal variables we created

3. Then, we don't need to pay attention to how the ThreadLocal variable is associated with Thread, just get/set directly


ThreadLocalMap is the container of many ThreadLocal variables we created, and this container is a member of the thread and is exclusively


The Key in ThreadLocalMap  is the reference to the ThreadLocal variable we created,

Therefore, when calling tl1.set or tl1.get, you can find yourself in the Map according to the tl1 reference, and read or update your own value


ThreadLocalMap is a member variable of the thread, so the current thread is obtained first when ThreadLocalMap is obtained.

Then read its ThreadLocalMap member (variable name threadLocals)


A variable of type ThreadLocal is equivalent to supporting the operation of ThreadLocalMap internally, saving us from putting the variable into the Map, and directly putting it into the Map with a set


In fact, if ThreadLocalMap opens the operation interface, we can define ordinary variables (not of ThreadLocal type),

Manually put  it in ThreadLocalMap, the effect should be similar,

In short  , variables of type ThreadLocal inherently support the operation of  ThreadLocalMap

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325853066&siteId=291194637