Use of Java threadlocal

Source: Internet
Author: User

1.ThreadLocal to solve concurrency problems with multithreaded threads
2.ThreadLocal is not a thread, but a local variable of thread, and when you use threadlocal to maintain a variable, threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread
You can change your copy independently, without affecting the replicas of other threads.
3. From the thread's point of view, the target variable is like a thread's local variable, which is the meaning of the "local" in the class name.
4. Thread-local variables are not a new Java invention, Java is not provided in language-level support (syntactically), but rather in a disguised way through the Threadlocal class to provide support.
Methods in the 5.ThreadLocal class: (Generics are supported after JDK5 version)
void set (T value)
Sets the value in the current thread copy of this thread local variable to the specified value
void Remove ()
Removes the value of this thread's local variable current thread
Protected T InitialValue ()
Returns the "initial value" of the current thread for this thread's local variables
T get ()
Returns the value in the current thread copy of this thread's local variable
The principle of 6.ThreadLocal:
How does threadlocal maintain a copy of a variable for each thread? In fact, the idea is simple: there is a map in the Threadlocal class that stores a copy of the variable for each thread, and the elements in the map
The key is a thread object, and the value corresponds to a variable copy of the thread
7. Simulate Threadlocal yourself:

 Public classsimplethreadlocal{PrivateMap Valuemap=collections.synchronizedmap (NewHashMap ()); Public voidset (Object newvalue) {valuemap.put (Thread.CurrentThread (), newvalue);//The key is a thread object, and the value is a copy of the variable for this thread} PublicObject Get () {Thread CurrentThread=Thread.CurrentThread (); Object o=valuemap.get (CurrentThread);//returns the variable corresponding to this threadif(o==NULL&&!Valuemap.containskey (CurrentThread)) {//If it doesn't exist in the map, save it in the map.o=InitialValue (); Valuemap.put (currentthread,o);}returno;} Public voidRemove () {Valuemap.remove (Thread.CurrentThread ());} Public voidInitialValue () {return NULL;}}


8. Specific examples of using threadlocal:

 Public classsequencenumber{//Specify the initial value by overriding the Threadlocal InitialValue () method with an anonymous inner classPrivate StaticThreadlocal<integer> senum=NewThreadlocal<integer>(){protectedInteger InitialValue () {return0;}} PublicInteger Getnextnum () {Senum.set (Senum.get ()+1);returnsenum.get ();} Public Static voidMain (string[] args) {sequencenumber sn=NewSequenceNumber ();//3 threads share sn, each generating serial numbertestclient T1 =Newtestclient (SN); TestClient T2=Newtestclient (SN); testclient T3=Newtestclient (SN); T1.start (); T2.start (); T3.start ();}Private Static classTestClientextendsthread{Privatesequencenumber sn; Publictestclient (SequenceNumber sn) { This. sn=SN;} Public voidrun () {//Print 3 serial numbers per thread for(inti=0;i<3;i++) {System.out.println ("thread[" +thread.currentthread (). GetName () + ", sn[" +sn.getnextnum () + "]");}}}}

9. The following is a complete example of an executable threadlocal:

        Public classThreadlocalexample { Public Static classMyrunnableImplementsRunnable {PrivateThreadLocal ThreadLocal =NewThreadLocal (); @Override Public voidrun () {Threadlocal.set (int) (Math.random () *100D)); Try{Thread.Sleep (2000); } Catch(Interruptedexception e) {} System.out.println (Threadlocal.get ()); }        }         Public Static voidMain (string[] args) {myrunnable sharedrunnableinstance=Newmyrunnable (); Thread Thread1=NewThread (sharedrunnableinstance); Thread thread2=NewThread (sharedrunnableinstance);             Thread1.start ();        Thread2.start (); }    }

The example above creates a myrunnable instance and passes the instance as a parameter to two threads. Each of the two threads executes the run () method, and each holds a different value on the threadlocal instance. If they are not accessing the Threadlocal object and the called Set () method is synchronized, the second thread overrides the value set by the first thread. However, because they are accessing a Threadlocal object, none of the two threads can see the value saved by the other. That is, they have access to two different values.

Use of Java 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.