Java's threadlocal

Source: Internet
Author: User

The ThreadLocal data is stored in one thread and does not require lock synchronization. Theoretically ThreadLocal can be

So that a variable has a copy on each thread. ThreadLocal is commonly used to mask private variables of a thread, such as "and

or other resources. Also, it is used to maintain counters, statistics, or ID generation for each thread

Manager


See the Get method definitions commonly used by threadlocal:

  Public T get () {

        Thread T = Thread.CurrentThread ();

        Threadlocalmap map = getmap (t);

        if (map! = null) {

            Threadlocalmap.entry E = Map.getentry (this);

            if (E! = null) {

              &N Bsp @SuppressWarnings ("unchecked")

                T result = (t) e.value;

                return result;

           }

       }

        return setinitialvalue ();

   }


Threadlocalmap Getmap (Thread t) {

return t.threadlocals;

}


You can know that each thread has a threadlocal.threadlocalmap threadlocals inside, and the maintenance of this map is performed by Threadlocal. And it's initialized to be lazily.

The generation of the current nexthashcode for each threadlocal , and the generation of its index within the THREADLOCALMAP internal array, can be seen in the source code.


Java's threadlocal

Related Article

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.