Interview question: Thorough understanding of ThreadLocal

Java .lang.ThreadLocal   was provided as early as the JDK 1.2 version, and ThreadLocal provides a new idea for solving the concurrency problem of multi-threaded programs. Using this utility class, you can write beautiful multi-threaded programs very concisely.

  When using ThreadLocal to maintain variables, ThreadLocal provides an independent copy of the variable for each thread that uses the variable , so each thread can change its own copy independently without affecting the copies corresponding to other threads.

  From the thread's point of view, the target variable is like the thread's local variable, which is what the "Local" in the class name means.

  So, coding thread-local variables in Java is relatively unwieldy, so thread-local variables are not very popular among Java developers.

ThreadLocal interface method

The ThreadLocal class interface is very simple, there are only 4 methods, let's take a look at it first:

  • void set(Object value) Sets the value of the thread-local variable of the current thread.
  • public Object get() This method returns the thread local variable corresponding to the current thread.
  • public void remove() deletes the value of the local variable of the current thread, in order to reduce the memory usage, this method is a new method in JDK 5.0. It should be pointed out that when the thread ends, the local variables corresponding to the thread will be automatically garbage collected, so it is not necessary to explicitly call this method to clear the local variables of the thread, but it can speed up the speed of memory reclamation.
  • protected Object initialValue() returns the initial value of the thread-local variable. This method is a protected method, apparently designed for subclasses to override. This method is a deferred call method that is executed when the thread calls get() or set(Object) for the first time, and only once. The default implementation in ThreadLocal simply returns a null.

  It is worth mentioning that in JDK5.0, ThreadLocal already supports generics, and the class name of this class has been changed to ThreadLocal<T>. The API methods have also been adjusted accordingly. The API methods of the new version are void set(T value), T get() and T initialValue().

  How does ThreadLocal maintain a copy of the variable for each thread? In fact, the idea of ​​​​implementation is very simple: there is a Map in the ThreadLocal class, which is used to store the variable copy of each thread. The key of the element in the Map is the thread object, and the value corresponds to the variable copy of the thread.

 

 

 

Comparison of Thread Synchronization Mechanisms

  What are the advantages of ThreadLocal compared to thread synchronization mechanisms ? Both ThreadLocal and thread synchronization mechanisms are designed to solve the access conflict problem of the same variable in multiple threads.

  In the synchronization mechanism, the lock mechanism of the object ensures that only one thread accesses the variable at the same time . At this time, the variable is shared by multiple threads. Using the synchronization mechanism requires the program to carefully analyze when to read and write the variable, when to lock an object, and when to release the object lock and other complicated issues. Program design and writing relatively difficult.

  ThreadLocal solves the concurrent access of multiple threads from another perspective . ThreadLocal will provide each thread with an independent copy of the variable, thereby isolating the access conflict of multiple threads to the data. Since each thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides thread-safe shared objects. When writing multi-threaded code, unsafe variables can be encapsulated into ThreadLocal.

  Since any type of object can be held in ThreadLocal, the get() provided by the lower version of JDK returns an Object object, which requires type conversion. But JDK 5.0 solves this problem well through generics, which simplifies the use of ThreadLocal to a certain extent. Listing 92 uses the new ThreadLocal<T> version of JDK 5.0.

  To sum up, for the problem of multi-threaded resource sharing, the synchronization mechanism adopts the method of " exchanging time for space ", while ThreadLocal adopts the method of "exchanging space for time" . The former only provides a variable for different threads to queue for access, while the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.

  Spring uses ThreadLocal to solve thread safety problems. We know that in general, only stateless beans can be shared in a multi-threaded environment. In Spring, most beans can be declared as singleton scopes. It is because Spring uses ThreadLocal to process non-thread-safe states in some beans (such as RequestContextHolder, TransactionSynchronizationManager, LocaleContextHolder, etc.), making them thread-safe, because stateful beans can be shared among multiple threads.

  The general Web application is divided into three layers: presentation layer, service layer and persistence layer. Corresponding logic is written in different layers, and the lower layer opens the function call to the upper layer through the interface. In general, all program calls from receiving a request to returning a response belong to the same thread

  The same thread runs through the three layers so that you can store some non-thread-safe variables in ThreadLocal according to your needs. In the calling thread of the same request response, all related objects refer to the same variable.

 

In the summary blog post, the summary is that one is the lock mechanism for time-for-space, and the other is for storage copy for space-for-time .

Guess you like

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