ThreadLocal tests job candidates

What is ThreadLocal

ThreadLocal is a local thread copy variable tool class. Each thread has a thread private data, and the variables between threads do not interfere with each other. In high concurrency scenarios, stateless calls can be realized.

ThreadLocal provides another way of thinking about thread safety. What we usually say about thread safety is mainly to ensure concurrent access to shared data, and to ensure data consistency through sychronized locks or CAS lock-free strategies.

ThreadLocal structure diagram


From the above structure diagram, we have glimpsed the core mechanism of ThreadLocal:

There is a Map inside each Thread thread.
Thread local object (key) and thread variable copy (value) are stored
in Map . Thread's internal Map is maintained by ThreadLocal, and ThreadLocal is responsible for obtaining and setting thread variable values ​​from the map.
For different threads, each time the copy value is obtained, other threads cannot obtain the copy value of the current thread, which forms the isolation of the copy and does not interfere with each other.

Let's look at an example.

The following example has 3 threads [thread#1],[thread#2],[thread#3] modify the class variable initValue, when the class variable is ThreadLocal, the modified values ​​of the three threads do not affect each other, and the printed results are all Is 66

In the above example, if three threads can modify the variables independently at the same time, the answer lies in the set() and get() methods of ThreadLocal.

Let's take a look at ThreadLocal

The ThreadLocal class provides the following core methods:

The get() method is used to obtain the value of the copy variable of the current thread.
The set() method is used to save the copy variable value of the current thread.
initialValue() is the initial copy variable value of the current thread.
The remove() method removes the copy variable value of the current future.
get() method

Guess you like

Origin blog.csdn.net/hongweideng/article/details/104391660