A brief analysis of Java ThreadLocal

Source: Internet
Author: User

1. Concept

Synchronized this kind of thread synchronization mechanism can solve multi-threaded concurrency problem, in this solution, multiple threads access to the same copy of the contents of the variable. To prevent concurrency errors that may occur during multithreaded access. Having to synchronize access to multiple threads means that multiple threads have to access or modify the value of the variable successively, which is a strategy for increasing the access time in exchange for thread security .

The Threadlocal class maintains its own unique copy of the variable for each thread. Each thread has its own independent variable, the competition conditions are completely eliminated, there is no need to synchronize these threads, they can be the maximum CPU scheduling, concurrent execution. And since each thread accesses the variable, it reads and modifies its own unique copy of the variable, and the variable is completely enclosed in each accessed thread, and the concurrency error may be completely eliminated. In contrast to the previous scenario, this is a strategy for exchanging space for thread security .

2. Example Analysis
6  Public classThreadlocaltest {7  8 //Create an integer thread-local variable9 Public Static FinalThreadlocal<integer> local =NewThreadlocal<integer>() {Ten @Override OneprotectedInteger InitialValue () { Areturn0; -         } -     }; the   - Public Static voidMain (string[] args)throwsinterruptedexception { -thread[] Threads =NewThread[5]; - for(intj = 0; J < 5; J + +) { +THREADS[J] =NewThread (NewRunnable () { - @Override + Public voidrun () { A//gets the local variable of the current thread and then accumulates 5 times at intnum =local.get (); - for(inti = 0; I < 5; i++) { -num++; -                     } -//reset the accumulated local variables - local.set (num); inSystem.out.println (Thread.CurrentThread (). GetName () + ":" +local.get ()); -   to                 } +}, "thread-" +j); -         } the   *  for(Thread thread:threads) { $ Thread.Start ();Panax Notoginseng         } -     } the } +  A Operation Result: theThread-0:5 +Thread-3:5 -Thread-2:5 $Thread-1:5 $Thread-4:5

As we can see, each thread's cumulative result is 5, each thread processes its own local variable value, and the threads do not affect each other.

3. In-depth source

How does the Threadlocal class implement this "different copy of the variable for each thread"? Let's take a look at how the source code of the Threadlocal set () method is implemented:

 Public voidset (T value) {Thread T=Thread.CurrentThread (); Threadlocalmap Map=Getmap (t); if(Map! =NULL) Map.set ( This, value); ElseCreatemap (t, value);}  PublicT Get () {//gets the current thread of executionThread T =Thread.CurrentThread (); //gets the Threadlocalmap instance of the current threadThreadlocalmap map =Getmap (t); //If map is not empty, it means that the thread already has a Threadlocalmap instance    if(Map! =NULL) {        //map to save all thread local variables of thread, we are going to find the current thread local variableThreadlocalmap.entry e = Map.getentry ( This); //if the current thread local variable exists in this map, its corresponding value is returned        if(E! =NULL)            return(T) E.value; }    //If the map does not exist or the current thread local variable does not exist in the map, the initial value is returned    returnsetinitialvalue ();} PrivateT Setinitialvalue () {//get initialization value, InitialValue is the method we covered beforeT value =InitialValue (); Thread T=Thread.CurrentThread (); Threadlocalmap Map=Getmap (t); //If map is not empty, the initialization value is placed in the Threadlocalmap object of the current thread    if(Map! =NULL) Map.set ( This, value); Else        //The current thread uses the local thread variable for the first time, and the map needs to be initializedCreatemap (t, value); //returns the initialization value    returnvalue;}

void Createmap (Thread T, T firstvalue) {
T.threadlocals = new Threadlocalmap (this, firstvalue);
}

Threadlocal has an internal class threadlocalmap, the implementation of this class accounted for the entire Threadlocal class source code more than half. The role of this threadlocalmap is critical, and it is a container for threads to actually save the thread's own local variables. Each thread has its own separate instance of Threadlocalmap, and all its local variables are saved to this map. First, the Getmap (thread T) method is used to get a threadlocalmap related to the current thread, and then the value of the variable is set to the Threadlocalmap object, of course, if the Threadlocalmap object obtained is empty, is created by using the Createmap method.

// returns the Threadlocals property of the thread object directly threadlocalmap Getmap (Thread t) {    return  t.threadlocals;}

The thread object has an attribute threadlocals of type Threadlocalmap, which is dedicated to saving all of its thread-local variables. This property is null when the thread object is initialized. Therefore, the Threadlocals property needs to be initialized for the first time that a thread object is used on a thread-local variable.

4. Summary

The secret of thread isolation lies in the Threadlocalmap class. Threadlocalmap is a static inner class of the Threadlocal class that implements the setting and acquisition of key-value pairs (as compared to the map object), each of which has a separate threadlocalmap copy that stores values that can only be read and modified by the current thread. The Threadlocal class implements the isolation of variable access in different threads by manipulating a threadlocalmap copy of each line thread. Because the variables are unique to each thread, there is no concurrency error at all. Another thing is that the key in the Threadlocalmap stored key-value pair is the Threadlocal object that the this object points to, and the value is the object you set.

A brief analysis of Java ThreadLocal

Related Article

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.