The use and understanding of threadlocal

Source: Internet
Author: User

Threadlocal is a threadlocalvariable (thread local variable) that provides a copy of a variable value for each thread that uses the variable, and from a thread point of view, each thread maintains an implicit reference to its thread local variable copy. As long as the thread is active and the ThreadLocal instance is accessible, all copies of its thread-local instances are garbage collected after the threads have disappeared (unless there are other references to those replicas).

How does threadlocal maintain a copy of a variable for each thread? In fact, the idea of implementation is simple, there is a map in the Threadlocal class that stores a copy of each thread's variable. To sum up, for the problem of multi-thread resource sharing, the synchronization mechanism adopts the way of "time-changing Space", and threadlocal adopts the way of "changing time by Space". The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other. Instance:
 Public classStudent {Private intAge = 0;//Age      Public intGetage () {return  This. Age; }      Public voidSetage (intAge ) {         This. Age =Age ; }} Public classThreadlocaldemoImplementsRunnable {//Create thread local variable studentlocal, which you will find to save student object later    Private Final StaticThreadLocal studentlocal =NewThreadLocal ();  Public Static voidMain (string[] agrs) {Threadlocaldemo TD=NewThreadlocaldemo (); Thread T1=NewThread (TD, "a"); Thread T2=NewThread (TD, "B");        T1.start ();    T2.start (); }      Public voidrun () {accessstudent (); }     /*** Example Business method, used to test*/     Public voidaccessstudent () {//gets the name of the current threadString Currentthreadname =Thread.CurrentThread (). GetName (); System.out.println (Currentthreadname+ "is running!"); //generate a random number and printRandom random =NewRandom (); intAge = Random.nextint (100); System.out.println ("Thread" + Currentthreadname + "set Age to:" +Age ); //gets a student object and inserts the age of the random number into the object propertiesStudent Student =getstudent ();        Student.setage (age); System.out.println ("Thread" + Currentthreadname + "First read is:" +student.getage ()); Try{Thread.Sleep (500); }        Catch(Interruptedexception ex) {ex.printstacktrace (); } System.out.println ("Thread" + Currentthreadname + "second read" is: "+student.getage ()); }     protectedStudent getstudent () {//get local thread variable and cast to student typeStudent Student =(Student) studentlocal.get (); //The first time the thread executes this method, Studentlocal.get () must be null        if(Student = =NULL) {            //creates a student object and saves it to the local thread variable studentlocalStudent =NewStudent ();        Studentlocal.set (student); }        returnstudent; }}

Operation Result:

A is running!
Thread A set age to:76
B is running!
Thread B Set Age to:27
Thread A first read age is:76
Thread B First read age is:27
Thread A second read age is:76
Thread B Second Read age is:27

Comparison of Threadlocal and synchronized:

Both threadlocal and synchonized are used to solve multi-threaded concurrent access. But there is an essential difference between threadlocal and synchronized. Synchronized is the mechanism by which a lock is used so that a variable or block of code can be accessed by only one thread at a time. Instead, Threadlocal provides a copy of the variable for each thread, so that each thread accesses the same object at a certain time, isolating data sharing from multiple threads. Synchronized, in contrast, is used to gain data sharing when communicating between multiple threads. Synchronized is used for data sharing between threads, while threadlocal is used for data isolation between threads. Of course threadlocal is not a substitute for synchronized, they deal with different problem domains. Synchronized is used to implement synchronization mechanisms and is more complex than threadlocal. Threadlocal general use steps: 1. In a multithreaded class (such as the Threaddemo Class), create a Threadlocal object threadxxx, which is used to hold the object xxx between the threads that need to be treated in isolation. 2. In the Threaddemo class, create a Method getxxx () that gets the data to be quarantined, and in the method it is judged that if the Threadlocal object is null, a new () object should be created to isolate the access type and cast to the type to be applied. 3, in the Threaddemo class of the Run () method, through the GetXXX () method to obtain the data to be manipulated, so that each thread can be guaranteed to correspond to a data object, at any time the operation of this object.

The use and understanding of threadlocal

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.