Java--threadlocal class

Source: Internet
Author: User



first, the introduction of Threadlocal


/* Test ThreadLocal Object * ThreadLocal: This class provides a thread-local variable.  * These variables are independent in the case of shared access in different line thread (must be accessed through the get and set methods). * It is obvious that this class provides a mechanism to prevent the unsafe mechanism of multi-threaded access. It is actually a variable that is stored locally in a thread, instead of by a shared variable. This depends on our use of the situation, if we do need to share data, it still must be through the synchronization mechanism to ensure the security of the data. * If there are situations where you want different threads to be kept separate from each other, it would be appropriate to use this.  ThreadLocal The class itself is not a variable to be accessed by the thread, and the member variable is the class. JDK1.5 adds a generic function to ThreadLocal, which is Threadlocal<t>, which is the local variable to thread. The thread accesses the variable T through ThreadLocal's get and set methods. ThreadLocal provides a mechanism that allows a thread to access it through this to access a variable of type T when it is a different copy. So access to the variable must pass the Threadlocal this class only provides two public methods, that is, the get () and the set () method to access. A protected method for Inintvalue () is also provided. The method is used to initialize the value of the variable. Note: InitValue (), by default, returns NULL. The Get method calls the InitValue method by default when the first call to get is called before the set is called. So if this method is not covered, it may cause the get to return null. Of course, this is not the case if you call a set.  But often in multi-threaded situations we cannot guarantee that each thread calls the set before calling get, so it is best to overwrite the initvalue so as not to cause a null pointer exception. * */


Test, in the absence of threadlocal:


public class Testthreadlocal {public static int a = 0;public static void Main (string[] args) {MyThread mythread=new Mythre AD (); Mythread.start (); for (int i=0;i<5;i++) {System.out.println (Thread.CurrentThread (). GetName () + ":" +a);}} public static class MyThread extends Thread {public void run () {for (int i=0;i<5;i++) {a=++a; System.out.println (Thread.CurrentThread (). GetName () + ":" +a);}}}

Test results:


Main:1main:2main:3main:4main:5thread-0:6thread-0:7thread-0:8thread-0:9thread-0:10

the results were confusing and the execution of the two threads was clearly crossed.


After using threadlocal:


public class Testthreadlocal {//public static int a = 0;public static threadlocal<integer> a=new Threadlocal<inte Ger> () {public Integer InitialValue () {//initializes the value of a to return 0;}}; public static void Main (string[] args) {MyThread mythread=new MyThread (), Mythread.start (); for (int i=0;i<5;i++) {//a= ++a;a.set (A.get () +1); System.out.println (Thread.CurrentThread (). GetName () + ":" +a.get ());} public static class MyThread extends Thread {public void run () {for (int i=0;i<5;i++) {//a=++a;a.set (A.get () +1); System.out.println (Thread.CurrentThread (). GetName () + ":" +a.get ());}}}

Results:


Thread-0:1thread-0:2thread-0:3thread-0:4thread-0:5main:1main:2main:3main:4main:5

After using the thread-local variables, we must read and write the variables through the get and set methods.


Two, Brief introduction threadlocal


 /** * Returns The current thread ' s "initial value" for this * thread-local variable.  This method is invoked the first * time a thread accesses the variable with the {@link #get} * method, unless The thread previously invoked the {@link #set} * method, in which case the <tt>initialValue</tt> method W  Ill not * is invoked for the thread. Normally, this method was invoked at * Most once per thread, but it could be invoked again in case of * subsequent in     Vocations of {@link #remove} followed by {@link #get}. * * <p>this implementation simply returns <tt>null</tt>; If the * programmer desires thread-local variables to a initial * value other than <tt>null</tt>  , <tt>ThreadLocal</tt> must is * subclassed, and this method overridden.     Typically, an * anonymous inner class would be used. * * @return The initial value for this thread-local */protected T InitialvaLue () {return null; }


The initialization of the variable is done here, and Null is returned by default, and it is recommended to override this method to ensure that the get has been set before the get error is prevented.


Public T get () {        Thread T = Thread.CurrentThread ();        Threadlocalmap map = getmap (t);        if (map! = null) {            Threadlocalmap.entry e = Map.getentry (this);            if (E! = null)                return (T) e.value;        }        return Setinitialvalue ();    }

In the Threadlocal class, there is an internal static class Threadlocalmap, which holds the object with key as the current threadlocal.


public void Set (T value) {        Thread T = Thread.CurrentThread ();        Threadlocalmap map = getmap (t);        if (map! = null)            Map.set (this, value);        else            createmap (t, value);    }



The Set method is similarly similar, the value usually put in threadlocal is usually used in these two methods to operate, oh, and remove:


public void Remove () {         Threadlocalmap m = Getmap (Thread.CurrentThread ());         if (M! = null)             m.remove (this);     }

A lot of code のの .... Look at the general first, and then switch back to our spring source parsing, this is only a small episode.







Java--threadlocal class

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.