A brief explanation of ThreadLocal
"TLDR: This article introduces the ThreadLocal class in Java, which is a thread-safe mechanism for handling shared variables. ThreadLocal provides an independent copy of data for each thread and manages these copies through the get(), set() and remove() methods. Although ThreadLocal can solve the thread safety problem, a better solution is to use the synchronized keyword. The article also provides a sample code showing how to use ThreadLocal to implement multi-threaded programming."
#ThreadLocal brief explanation
ThreadLocal is a way to handle shared variables in multiple threads. It solves the problem of thread unsafety by assigning a copy of the shared variable to each thread.
Specifically, in Java, each thread's Thread class has a ThreadLocalMap data structure named threadLocals, which is used to store data unique to this thread.
There are three core methods in ThreadLocal:
-
get() method: here is to read the required value from
ThreadLocalMap -
set() method: here is to store a copy of the shared variable in
ThreadLocalMap -
remove() method: This is to remove the copy variable from
ThreadLocalMap
Note that the life cycle of the ThreadLocal variable has nothing to do with the life cycle of the thread. That is to say, even if the thread has ended, if the remove() method has not been called, then the ThreadLocal variable still exists.
Generally speaking, a better solution to deal with thread unsafe issues of shared variables is to use the @synchronized keyword.
Sample code:
//Create a class to implement the Runable interface and implement the run method to implement multi-threading
public class Test implements Runnable {
//Define ThreadLocal variable
private final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
// Implement a child thread
@Override
public void run () {
System.out.println("Enter child thread");
threadLocal.set((int) (Math.random() * 100));
System.out.println("Thread Id: " + Thread.currentThread().getId() + " - Value: " + threadLocal.get());
// If remove is not called, this variable will not be released even if the thread ends, which means that its life cycle has nothing to do with the thread that created it.
threadLocal.remove();
}
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
//Create three threads
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
Thread thread3 = new Thread(test);
thread1.start(); //Switch the thread's status to RUNABLE
thread2.start();
thread3.start();
thread1.join(); // Wait for this thread to complete execution
thread2.join();
thread3.join();
}
}
Multi-threading knowledge review:
When implementing multi-threading in Java, it must be started through the start() method. If the run() method is called directly, it will still be executed in the current thread, not the child thread.
If join() is called first instead of start(), then the current thread may wait for a non-existent child thread, and a deadlock may occur.