I. Overview
Before we discussed the issue of thread safety, we ensure thread safety by locking or using lock-free.
Of course lock-free performance will get better. But the core of their essence is to ensure the atomicity of the resources accessed.
Then let's recall the conditions under which the thread safety problem occurs:
[1] Multi-threaded concurrency
[2] Shared resources
[3] Non-atomic operations on shared resources
If we break the shared resource, can we also guarantee thread safety?
The answer is yes, ThreadLoacl can help us implement thread-level local variables.
2. Definition of ThreadLocal
[1] get() : get the value
[2]set() : set value
[3]remove() : remove value
Now we demonstrate the use of ThreadLocal, which defines thread-level local variables.
public class ThreadLocalTest { private final ThreadLocal<Integer> local = new ThreadLocal<Integer>(); public ThreadLocalTest() { local.set(0); } public static void main(String[] args) { ThreadLocalTest test = new ThreadLocalTest(); test.local.set(0); new Thread(new Runnable() { @Override public void run() {System.out.println ( " The value of the child thread: " + test.local.get ( ) ); } }).start(); // The thread stack of the main thread has local, which is now 0 System.out.println ( " The value of the main thread's local is: " + test.local.get ( ) ); } }
We created an object containing a member variable of ThreadLocal, and then modified its value to 0. Then printed this variable from the main thread and the child thread respectively, and we found that the results are as follows:
The main thread's local value is: 0 The child thread's value is: null
The value of the child thread is null, indicating that a copy has occurred in the child thread. The variables in the child thread and the main thread are not shared.
3. Analysis
We saw the basic use of ThreadLocal earlier, and ThreadLocal can help us store thread variables.
For example, in our Servlet, the model itself is a multi-threading model.
Now we can use ThreadLocal to help us store data.