ThreadLocal (i)

Source: Internet
Author: User

In this paper, we refer to http://lavasoft.blog.51cto.com/62575/51926/to rewrite the program.

I. Overview

What is threadlocal? In fact, Threadlocal is not a local implementation version of a thread, it is not a threaded, but a threadlocalvariable (thread local variable). Perhaps it would be more appropriate to name it Threadlocalvar. The thread local variable (ThreadLocal) function is very simple, that is, for each thread that uses the variable to provide a copy of the value of a variable, is a special thread binding mechanism in Java, is that each thread can independently change its own copy, and does not conflict with the copy of other threads.

From a thread's point of view, each thread maintains an implicit reference to a copy of its thread's local variables, as long as the thread is active and the ThreadLocal instance is accessible, and all copies of its thread's local instance are garbage collected after the threads have disappeared (unless there are other references to those replicas).

The data accessed through threadlocal is always related to the current thread, that is, the JVM binds the private local instance access space for each running thread, thus providing an isolation mechanism for concurrent access problems that often occur in multithreaded environments.

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.

Second, API description

ThreadLocal ()

Creates a thread-local variable.

T get ()

Returns the value in the current thread copy of this thread's local variable, and if this is the first time a thread calls the method, creates and initializes the copy.

Protected T InitialValue ()

Returns the initial value of the current thread for this thread's local variables. This method is called at most once per access thread to get the local variable for each of the threads, that is, the first time the thread accesses the variable using the Get () method. If the thread calls the set (T) method before the Get method, then the InitialValue method is not called in the threads.

If the implementation returns only NULL, and if the programmer wants to initialize a thread-local variable to a value other than NULL, the subclass must be created for ThreadLocal and overridden by this method. Typically, anonymous inner classes are used. A typical implementation of InitialValue invokes an appropriate construction method and returns the newly constructed object.

void Remove ()

Removes the value of this thread's local variable. This may help reduce the storage requirements for thread-local variables. If you access this thread's local variable again, by default it will have its initialvalue.

void set (T value)

Sets the value in the current thread copy of this thread's local variable to the specified value. Many applications do not require this functionality, they rely only on the InitialValue () method to set the value of a thread-local variable.

The InitialValue method is generally overridden in a program to give a specific initial value.

Iii. examples

Create a bean that sets the bean properties through different thread objects, guaranteeing the independence of the individual thread bean objects.

Example code:

 PackageCom.yangyang;ImportJava.util.Random; Public classThreadlocaltestImplementsrunnable{/*** Student Entity *@authorShunyang * @date March 5, 2015 PM 3:34:58*/     Public classstudent{/**Age **/        Private intAge ;  Public intGetage () {returnAge ; }         Public voidSetage (intAge ) {             This. Age =Age ; }            }        //Create thread-local variable studentlocal, which is used to save student objects     Public Final StaticThreadLocal studentlocal=NewThreadLocal ();  Public Static voidMain (string[] args) {threadlocaltest TD=Newthreadlocaltest (); Thread T1=NewThread (TD, "a"); Thread T2=NewThread (TD, "B");        T1.start ();    T2.start (); } @Override Public voidrun () {accessstudent (); }              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 =GetStudent2 ();            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 ()); }         /*** Use local thread variable to get * @date March 5, 2015 PM 3:37:14 *@authorShunyang *@return          */        protectedStudent getStudent1 () {//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; }                /*** Direct NEW * @date March 5, 2015 PM 3:37:03 *@authorShunyang *@return         */        protectedStudent GetStudent2 () {return NewStudent (); }}

At this point, because the student in the Accessstudent method is a local variable, no matter the invocation

Student Student = GetStudent1 ();

or call the

Student Student = GetStudent2 ();

You can see that a, b two threads, age prints at different times are exactly the same value,

At this time the role of threadlocal is not reflected.

However, if the Accessstudent method is changed to:

 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 properties//Student Student = GetStudent2 ();GetStudent2 (). Setage (age); System.out.println ("Thread" + Currentthreadname + "First read is:" +GetStudent2 (). Getage ()); Try{Thread.Sleep (500); }            Catch(Interruptedexception ex) {ex.printstacktrace (); } System.out.println ("Thread" + Currentthreadname + "second read" is: "+GetStudent2 (). Getage ()); }

When you do not use a local variable and do not use the threadlocal GetStudent2 () method, the result is:

found that a.b two threads could not read the correct values,

At this point, if you call the GetStudent1 () method with threadlocal, the result is:

You can see that a, b two threads age at different times the value of printing is exactly the same, through the use of threadlocal, both multithreading concurrency, the security of the data.

Iv. Summary

Threadlocal mainly solves the problem that the data data in multi-threading is inconsistent with concurrency. Threadlocal provides a copy of the data that is accessed concurrently in each thread and runs the business through the access replica, which results in memory consumption, which greatly reduces the performance cost of thread synchronization and reduces the complexity of thread concurrency control.

Threadlocal cannot use atomic types, only object types. Threadlocal is much simpler to use than 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.

V. General steps for the use of threadlocal

1. In a multithreaded class (such as the Threaddemo Class), create a Threadlocal object threadxxx, which is used to save the object xxx between 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.

ThreadLocal (i)

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.