Understand the ThreadLocal class

Source: Internet
Author: User

1. ThreadLocal provides java. lang. ThreadLocal as early as JDK 1.2. ThreadLocal provides a new idea to solve the concurrent problem of multi-threaded programs. Using this tool class, you can easily compile beautiful multi-threaded programs. ThreadLocal, as its name implies, is not a thread, but a localized object of the thread. When ThreadLocal is used to maintain a variable for a multi-threaded object, ThreadLocal allocates an independent copy of the variable for each thread that uses the variable. Therefore, each thread can change its own copy independently without affecting the copies corresponding to other threads. From the thread perspective, this variable is like a Local variable of the thread, which is also the meaning of "Local" in the class name.
API explanation: This class providesThread-local variable. These variables are different from their common counterparts, because each thread accessing a variable (through its get or set method) has its own local variable, which is independent of the initialization copy of the variable.ThreadLocal instances are usually private static fields in the class.,They want to associate the status with a thread (for example, user ID or transaction ID).
Examples of using APIs:

import java.util.concurrent.atomic.AtomicInteger;public class ThreadId {// Atomic integer containing the next thread ID to be assignedprivate static final AtomicInteger nextId = new AtomicInteger(0);// Thread local variable containing each thread's IDprivate static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {@Overrideprotected Integer initialValue() {return nextId.getAndIncrement();}};// Returns the current thread's unique ID, assigning it if necessarypublic static int get() {return threadId.get();}}
Each thread maintains an implicit reference to its local variable copy, as long as the thread is active and the ThreadLocal instance is accessible. After the thread disappears, all copies of the local instance of the thread will be garbage collected (unless there are other references to these copies ).
2. Implementation and Method Introduction of the ThreadLocal class there are four methods for the ThreadLocal class: void set (Object value): set the value of the local variable of the current thread;
Public Object get (): This method returns the local variable of the thread corresponding to the current thread;
Public void remove (): deletes the value of the local variable of the current thread to reduce memory usage. This method is added to JDK 5.0. It should be noted that when the thread ends, the local variables of the thread will be automatically reclaimed, so explicitly calling this method to clear the local variables of the thread is not a required operation, but it can speed up memory recovery;
Protected Object initialValue (): returns the initial value of the local variable of the thread. This method is a protected method, apparently designed to overwrite the subclass. This method is a delayed call method. It is executed only once when the thread calls get () or set (Object) for 1st times. The default implementation in ThreadLocal directly returns a null value.
In Java, if a variable is to be accessed by multiple threads, you can use the volatile keyword to declare it as "changeable". If a variable is exclusive to a thread, java does not have a keyword like _ declspec (thread) in C ++. However, you can still use the ThreadLocal class to implement local thread storage. Each Thread has a ThreadLocalMap object., This object stores a group with ThreadLocal. threadLocalHashCode is the key, with the local thread variable as the value of the K-V value pair, ThreadLocal object is the current thread ThreadLocalMap access entry, each ThreadLocal object contains a unique threadLocalHashCode value, with this value, you can retrieve the corresponding local thread variable in the thread K-V value pair.
How does ThreadLocal maintain copies of variables for each thread? In fact, the implementation idea is very simple: there is a Map in the ThreadLocal class, which is used to store a copy of the variable 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.
Simple implementation version (similar to jdk implementation ):
Public class SimpleThreadLocal {private final Map valueMap = Collections. synchronizedMap (new HashMap (); public void set (Object newValue) {// The key is the thread Object, and the value is the valueMap of the variable copy of the thread. put (Thread. currentThread (), newValue);} public Object get () {Thread currentThread = Thread. currentThread (); // return the variable Object o = valueMap corresponding to this thread. get (currentThread); // if the Map does not exist, store it in the Map. if (o = null &&! ValueMap. containsKey (currentThread) {o = initialValue (); valueMap. put (currentThread, o);} return o;} public void remove () {valueMap. remove (Thread. currentThread ();} public Object initialValue () {return null ;}}

3. A multithreading example shows how to use ThreadLocal through a specific instance.
Public class SequenceNumber {// use an anonymous internal class to overwrite the initialValue () method of ThreadLocal and specify the initial value private static ThreadLocal <Integer> seqNum = new ThreadLocal <Integer> () {@ Overridepublic Integer initialValue () {return 0 ;}}; // gets the next sequence value public int getNextNum () {seqNum. set (seqNum. get () + 1); return seqNum. get ();} public static void main (String [] args) {SequenceNumber sn = new SequenceNumber (); // three threads share the sn, their respective serial numbers are TestClient t1 = new TestClient (sn); TestClient t2 = new TestClient (sn); TestClient t3 = new TestClient (sn); t1.start (); t2.start (); t3.start ();} private static class TestClient extends Thread {private final SequenceNumber sn; public TestClient (SequenceNumber sn) {this. sn = sn ;}@ Overridepublic void run () {// three sequence values for (int I = 0; I <3; I ++) {System. out. println ("thread [" + Thread. currentThread (). getName () + "] sn [" + sn. getNextNum () + "]") ;}}}
Check the output information below. We find that the serial numbers generated by each thread share the same Sequence Number instance, but they do not interfere with each other, instead, they generate independent serial numbers, because we provide separate copies for each thread through ThreadLocal.
thread[Thread-1] sn[1]thread[Thread-1] sn[2]thread[Thread-0] sn[1]thread[Thread-2] sn[1]thread[Thread-0] sn[2]thread[Thread-0] sn[3]thread[Thread-1] sn[3]thread[Thread-2] sn[2]thread[Thread-2] sn[3]
4. Conclusion ThreadLocal is essentially a solution for concurrent multi-threaded access from another perspective. ThreadLocal provides an independent copy of variables for each thread, thus isolating multiple threads from Data Access conflicts. Because every thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides thread-safe object encapsulation. When writing multi-threaded code, you can encapsulate insecure variables into ThreadLocal.To sum up, for the problem of multi-thread resource sharing, The synchronization mechanism adopts the "time-for-space" method.: Serializes access and shares objects. While ThreadLocal adopts the "change space for Time" method.: Parallel access, exclusive object. The former provides only one copy of the variable, allowing different threads to queue for access, while the latter provides a copy of the variable for each thread. Therefore, the former can be accessed simultaneously without affecting each other.

Bibliography: deep understanding of JVM and Spring3.x development practices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.