Threadlocal source parsing, and the relationship between Threadlocal, Threadlocalmap, Thread three

Source: Internet
Author: User
The relationship between ThreadLocal, Threadlocalmap and Thread three

Threadlocalmap is the inner class of ThreadLocal and there is a THREADLOCALMAP member variable in Thread threadlocals
ThreadLocal Source parsing see below, JDK about ThreadLocal API

threadlocal class Get method source code

Public Object Get ()
    {
        Thread thread = Thread.CurrentThread ();
        Threadlocalmap threadlocalmap = getmap (thread);
        if (threadlocalmap! = null)
        {
            Threadlocalmap.entry Entry = Threadlocalmap.getentry (this);
            if (entry! = NULL)
                return entry.value;
        }
        return Setinitialvalue ();
    }

Private Object Setinitialvalue ()
    {
        Object obj = InitialValue ();
        Thread thread = Thread.CurrentThread ();
        Threadlocalmap threadlocalmap = getmap (thread);
        if (threadlocalmap! = null)
            Threadlocalmap.set (this, obj);
        else
            createmap (thread, obj);
        return obj;
    }

Protected Object InitialValue ()
    {
        return null;
    }
When get a value,
Gets the current thread that calls the Getmap method to get the current thread's threadlocalmap, if the threadlocalmap! = NULL is obtained, then the value saved in Threadlocalmap is returned to the caller. If the obtained threadlocalmap = = NULL then calls the Setinitialvalue method, the InitialValue method is called in the Setinitialvalue method, and the return value of the InitialValue method, obj, is saved to Threadlocalmap, and then returns the return value of obj to the caller.
Threadlocal Class Set method source code
public void Set (Object obj)
    {
        Thread thread = Thread.CurrentThread ();
        Threadlocalmap threadlocalmap = getmap (thread);
        if (threadlocalmap! = null)
            Threadlocalmap.set (this, obj);
        else
            createmap (thread, obj);
    }

Threadlocalmap getmap (thread thread)
    {
        return thread.threadlocals;
    }

void Createmap (thread thread, Object obj)
    {
        thread.threadlocals = new Threadlocalmap (this, obj);
    }

When set a value, gets the current thread, calls the Getmap method to get the current thread's threadlocalmap, if obtained threadlocalmap = = NULL Then call Createmap method to create a threadlocalmap, and will obj is put into the threadlocalmap. (Note: The key in Threadlocalmap is Threadlocal,value is the input obj parameter.) Why Threadlocalmap in key is ThreadLocal, because a thread can have multiple ThreadLocal)

Threadlocal Class Remove method source code
public void Remove ()
    {
        Threadlocalmap threadlocalmap = Getmap (Thread.CurrentThread ());
        if (threadlocalmap! = null)
            threadlocalmap.remove (this);
    }

Delete the value corresponding to the current threallocal

Instance Code
public static void Main (string[] args) {
		threadlocal<string> tl = new threadlocal<string> ();
		String str = Tl.get ();
		System.out.println ("Output string:" + str);
	}
Output result output
string: null public

static void Main (string[] args) {
	threadlocal<string> tl = new threadlocal< String> () {
		@Override
		protected String initialvalue () {
			return "LP";
		}
	};
	String str = Tl.get ();
	System.out.println ("Output string:" + str);
}

Output Output
string: LP

As for why the output is not the same, I want to fight to see the above source parsing should understand it.

If you do not want to override the InitialValue method in ThreadLocal, you can call the Set method before calling the Get method, as in the following public

static void Main (string[] args) {
	threadlocal<string> tl = new threadlocal<string> ();
	Tl.set ("LP");
	String str = Tl.get ();
	System.out.println ("Output string:" + str);
}

Output result output
string: LP



Add

ThreadLocal's slightly less thread-safe cousin, inheritablethreadlocal

The

ThreadLocal class has a relative, inheritablethreadlocal, which works in a similar way, but applies to a completely different kind of application. When you create a thread, if you save the values of all the  InheritableThreadLocal  objects, those values are also automatically passed to the child thread. If a child thread calls  InheritableThreadLocal   get ()  , then it will see the same object as its parent thread. To protect thread security, you should use INHERITABLETHREADLOCAL&NBSP only for immutable objects (objects whose state is never changed once created), because objects are shared by multiple threads.  InheritableThreadLocal  is suitable for path data from a parent line to a child thread, such as a user ID or a transaction ID (transaction ID), but not a stateful object, such as a jdbc  connection .






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.