Java High concurrency Programming (ix)--threadlocal

Source: Internet
Author: User

If a lock is a thread-ordered scramble for resources, then threadlocal is to have a resource for each thread.

For example, the lock is for 100 people to compete for a pen area to write, threadlocal is 100 people each have a pen, in the turn when they write.

Write a simple example:

 Public classDemoImplementsrunnable{StaticThreadlocal<test> tl=NewThreadlocal<test>(); Static classTest {PrivateInteger in;  PublicInteger Getin () {returnIn ;} Test (Integer in) { This. in=In ;} }     Public Static voidMain (string[] args) {Executorservice es=executors.newfixedthreadpool (10);  for(inti=0;i<100;i++) {Es.submit (Newdemo ()); }    }     Public voidrun () {Tl.set (NewTestNewRandom (). Nextint (100))); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace ();    } System.out.println (Tl.get (). Getin ()); }}

The demo has a test inner class, there are 100 threads, each thread has a test class exists threadlocal there, each thread accesses its own test, does not affect each other.

Next look at the principle of threadlocal, from the Set () method:

 Public void set (T value) {        = thread.currentthread ();         = Getmap (t);         if NULL )            Map.set (this, value);         Else             createmap (t, value);    }

First get the current working thread, and then get a threadlocalmap,threadlocalmap is its inner class:

Static class Threadlocalmap {        staticclassextends weakreference<threadlocal>  {            Object value;            Entry (ThreadLocal K, Object v) {                super(k);                 = v;            }        }
、、、、、、、、、}

It can be seen as something similar to HashMap, with threadlocal as key,

Then enter the Getmap () method:

threadlocalmap Getmap (Thread t) {        return  t.threadlocals;    }

Get the thread threadlocals directly, go to thread,

null;

You can see that the thread maintains a threadlocal.threadlocalmap, goes back to the set method, and now we know that Getmap () gets a threadlocal inner class with thread maintenance, and now it's empty, go to else, Enter Createmap ():

void Createmap (Thread T, T firstvalue) {        new threadlocalmap (this, firstvalue);    }

Assigning a value to the threadlocals in thread, itself as a key, needs to be maintained as value.

After reading the set method, look at the Get () method:

 Public T Get () {        = thread.currentthread ();         = Getmap (t);         if NULL ) {            = map.getentry (this);             if NULL )                return  (T) e.value;        }         return Setinitialvalue ();    }

Very concise and clear, from the map to get value, nothing to say, want to know more detailed can see the source code.

In addition, because the Threadlocals reference is inside thread, thread does not exit, meaning it will persist, and if threads are maintained by a thread pool, threads may not exit.

So it's best to call the Remove () method when you're done with it.

Java High concurrency Programming (ix)--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.