Threadlocal the difference between shared thread local variables and thread synchronization mechanisms

Source: Internet
Author: User

Threadlocal is a good idea to solve thread safety problems by providing a separate copy of the variable for each thread to solve the conflicting problem of variable concurrency access. In many cases, threadlocal is easier and more convenient than using the synchronized synchronization mechanism to solve thread safety problems, and results programs have higher concurrency.

For the problem of multi-thread resource sharing, the synchronization mechanism adopts the way of "time-changing Space", and threadlocal adopts "space-changing Time". The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.

ThreadLocal Does not replace the synchronization mechanism, the problem areas are different.

1: Synchronization mechanism is in order to synchronize multiple threads to the same resources of concurrent access, is for multiple threads to communicate between the effective way;

2: While threadlocal is a data share that isolates multiple threads, there is essentially no sharing of variables among multiple threads, which of course does not require synchronization of multiple threads.

Import Java.util.random;public class Threadsocpesharedata {static threadlocal<integer> t = new threadlocal<     Integer> ();    public static void Main (string[] args) {for (int i=0;i<3;i++) {new Thread (new Runnable () {@Override             public void Run () {int data = new Random (). Nextint ();          System.out.println (Thread.CurrentThread (). GetName () + "has put" + data);        T.set (data);        Mythreadscopedata.getinstance (). SetName ("name" + data);    Mythreadscopedata.getinstance (). Setage ("Age" +data);    New A (). get ();    New B (). get ();     }}). Start ();     }} static class a{public void Get () {int data = T.get ();     Mythreadscopedata myData = Mythreadscopedata.getinstance (); System.out.println ("A" + thread.currentthread (). GetName () + "" + Data + mydata.getage () + mydata.getname ()/*ms.getname (     )*/);     }} static class b{public void Get () {int data = T.get (); System.out.println ("B" + Thread.currEntthread (). GetName () + "" + data);  }}}class mythreadscopedata{private Mythreadscopedata () {}private static threadlocal<mythreadscopedata> map = new Threadlocal<mythreadscopedata> ();p ublic static Mythreadscopedata getinstance () {Mythreadscopedata instance = Map.get (); if (instance = = null) {instance = new Mythreadscopedata (); Map.set (instance);} return instance;} private string Name;private string Age;public string GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getage () {return age;} public void Setage (String age) {this.age = age;}}

in fact, the variables we set in threadlocal are not stored by threadlocal, but by the thread object itself. When the user invokes set (object O) of the Threadlocal object, the method obtains the current thread through Thread.CurrentThread () and stores the variable in a map in thread. And the map key is the current threadlocal instance. Please look at the source code, this is the main two functions, can see threadlocal and thread of the call relationship:
public void Set (T value) {Thread T = Thread.CurrentThread ();  Threadlocalmap map = getmap (t);  if (map! = null) Map.set (this, value);  else Createmap (t, value);  } threadlocalmap Getmap (Thread t) {return t.threadlocals; public void Set (T value) {Thread T = Thread.CurrentThread (); Threadlocalmap map = getmap (t); if (map! = null) Map.set (this, value); else Createmap (t, value); } threadlocalmap Getmap (Thread t) {return t.threadlocals;}

Specifically, you can look at the source code, but one thing can be confirmed, is a copy of the thread created in threadlocal, can not call remove to do cleanup work, because the JVM in the discovery thread of the helper is no longer used, will be automatic garbage collection operations, I used to write the program when using threadlocal is often used after the completion of the cleanup work. (Prevents memory consumption and allows virtual machines to be cleared automatically if the number of replicas created is not too much)



Threadlocal the difference between shared thread local variables and thread synchronization mechanisms

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.