Java8 threadlocal Type source code detailed __JAVA8

Source: Internet
Author: User

JDK there is a threadlocal such a class, in fact, the name is not very close, this class is equivalent to the thread set a local variable. This makes it not possible to create multithreaded synchronization problems because multithreading accesses the same resource.

Because the Threadlocal class contains a copy of each thread, the threads don't interact with each other.

Now here the author will be from the point of view of the implementation of the source to tell you about the principle of threadlocal implementation.

First let's look at the implementation of the set () method.



All the authors will be given in the form of annotations.

public void Set (t value) {
     		//Get current thread object threads
      	 T = Thread.CurrentThread ();
	 Get a Map object, OK, so here's the problem. What kind of map object is this??
	 In fact, this Threadlocalmap object is a class

        Threadlocalmap map = getmap (t), similar to HashMap, which is implemented internally by the Threadlocal class.
	If the map is Non-null, put the current Threadlocal object and the parameters of the set () method into the map,
	//If it is not created.
        if (map!= null)
            Map.set (this, value);
        else
            createmap (t, value);
    



We can see that the Threadlocal class does define a Threadlocalmap class. Inside the realization and HashMap almost, the author does not point to go in to see.




One more point we'll go inside the Get () method to see the following.


Public T gets () {
	//Get current thread object threads
        t = Thread.CurrentThread ();
	Get the Threadlocalmap object, here we go. Getmap () method to look at 
        threadlocalmap map = getmap (t);
        if (map!= null) {
            Threadlocalmap.entry e = Map.getentry (this);
            if (e!= null) {
                @SuppressWarnings ("unchecked")
                T result = (t) e.value;
                return result;
            }
        return Setinitialvalue ();
    }


Compared to, see the previous explanation, readers also want to go in to see the realization of the getmap.

Threadlocalmap getmap (thread t) {//
     	from here you can see that the Threadlocalmap object is held by the current thread object,
	//But the maintenance work is done by the Threadlocal class. return
      	 t.threadlocals;
    }




The Createmap method holds the Threadlocalmap object inside the current thread object to be empty, and it
is called//from here we can also see that this class is threadlocal maintaining this relationship
void Createmap ( Thread T, t firstvalue) {
	
        t.threadlocals = new Threadlocalmap (this, firstvalue);
    }
Here we can come to the next conclusion.

The bottom layer of the threadlocal uses a map of its own implementation to store the values that the user set () comes in. The key of that map is the current Threadlocal object.

Some friends may ask. Now Threadlocal has only one object. Then the values in the map are not shared by other threads.

In fact, this is not, the author is also the beginning of this consideration-----------> This map should be stored in the current thread object and value. And not the one above.

Actually, it's not. Because the Threadlocal class itself implements a map object that is owned by itself within each thread object. Therefore, the Threadlocalmap objects within each thread object are different. So, the data inside is not to be shared by other threads, they are all their own.

Here I have written a demo to prove that each thread holds a different Threadlocalmap object.


Package multithread;
Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;


Import Java.util.concurrent.CyclicBarrier;
    
    Class Mythread implements Runnable {private Cyclicbarrier cyclicbarrier;
    
    /** * Threadlocalmap Object held by the first thread/static object object1 = NULL;
    
    /** * Threadlocalmap Object held by the second thread/static object object2 = NULL;
    Public Mythread (Cyclicbarrier cyclicbarrier) {this.cyclicbarrier = Cyclicbarrier;
        
        @Override public void Run () {ThreadLocal ThreadLocal = new ThreadLocal ();
        
        Thread thread = Thread.CurrentThread ();
        
        class<?> clazz = Threadlocal.class;
        
        Method createmap = null;
            
            try {method[] methods = Clazz.getdeclaredmethods ();
    
            Method createmapmethod = null;
            /** * To get the method object of Createmap by reflection * (method Method:methods) {if ("Createmap". Equals (Method.getname ()))
                    
                {Createmapmethod = method;
            
            
            } System.out.println (Createmapmethod);
                if (Createmapmethod!= null) {createmapmethod.setaccessible (true);
            Createmapmethod.invoke (threadLocal, Thread, "HelloWorld"); /** * Get the Localthreadmap object by executing the Getmap () method Getmap = Clazz
            
            . Getdeclaredmethod ("Getmap", Thread.class);
            
            Getmap.setaccessible (TRUE);
            
            System.out.println (Getmap.invoke (threadLocal, thread)); if ("Thread1". Equals (Thread.CurrentThread (). GetName ())) {Object1 = Getmap.invoke (threadloca
         l, thread);   } if ("Thread2". Equals (Thread.CurrentThread (). GetName ())) {Object2 = Getmap.i
            Nvoke (threadLocal, thread);
             All two threads, such as/** *, first get the Threadlocalmap object to execute the Run method in the anonymous class of the Runnable interface inside the Cyclicbarrier constructor.
             * Executed by the last completed thread.
        * * CYCLICBARRIER.AWAIT ();
        catch (Exception e) {e.printstacktrace (); }} public class Threadlocaltest {public static void main (string[] args) throws Nosuchfielde Xception, Illegalaccessexception, Interruptedexception, Nosuchmethodexception, Instantiationexception,
            invocationtargetexception {cyclicbarrier cyclicbarrier = new Cyclicbarrier (2, New Runnable () { @Override public void Run () {/** * To determine the THREADLOC held within two thread objects Almap is the same object/System.out.println (Mythread.object1 = = Mythread.object2);
    
        }
        } );
        
        Mythread mythread = new Mythread (cyclicbarrier);
        Thread thread1 = new Thread (mythread, "thread1");
        Thread thread2 = new Thread (mythread, "thread2");
        Thread1.start ();
        
    Thread2.start ();
 }
}



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.