The use of threadlocal and synchronized __java

Source: Internet
Author: User

I. Use of threadlocal

Implementation of Threadlocal:

[Java] View plain copy package com.sodao.lucene;           import  java.util.random;           Public class threadlocaltest  implements Runnable{                     ThreadLocal<Studen> studenThreadLocal = new  Threadlocal<studen> ();               @ override         public void run ()  {               String currentThreadName =  Thread.CurrentThread () getName ();               system.out.println (currentthreadname +  " is running ...");       &NBSP;&NBSP;&NBSP;&NBSP;    random random = new random ();              int age = random.nextint (MB);               system.out.println (currentthreadname +   " is set age: "   + age);               studen studen = getstudent ();  //through this method, For each thread is independent of the new student object, each thread's student object can set different values                studen.setage (age);               system.out.println (currentthreadname +  " is first get age: "  +  studen.getage ());              try  {                  thread.sleep (;    )           } catch  (interruptedexception e)  {                    E.printstacktrace ();              }               system.out.println (  currentthreadname +  " is second get age: "  + studen.getage ());                         }                    private studen getstudent ()  {               sTuden studen = studenthreadlocal.get ();               if  (Null == studen)  {                   studen = new studen ();                    Studenthreadlocal.set (Studen);              }               return studen;           }                public static void main (String[] args)  {              threadlocaltest t = new threadlocaltest ();       &NBsp;       thread t1 = new thread (T, "Thread A");               thread t2 = new  thread (T, "thread b");               T1.start ();              t2.start ();           }                }           class studen{           int age;               public int getage ()  {               return age;          }                public void setage (int age)  {               this.age = age;           }                }    

Implementation of synchronized:

[Java] View plain copy package com.sodao.lucene;           import  java.util.random;           Public class multithreadtest   implements Runnable{                     studen studen = new studen ();                      @Override           public void run ()  {               string currentthreadname = thread.currentthread (). GetName ();              system.out.println ( currentthreadname +  " is running&nbsp ...");               //Sync                synchronized  (Studen)  {                   random random = new random ();                  int age =  Random.nextint (;     )              studen.setage (age);                   system.out.println (currentthreadname +  " is set age: ")  + age);                   system.out.println (currentthreadname +  "is first get age: "  +  studen.getage ()  ); &NBSP;&NBsp;                try {                        thread.sleep (        );          } catch  (interruptedexception e)  {                       E.printstacktrace ();                   }                   system.out.println (currentthreadname +  " is second get age: "  +  studen.getage ()  );                   &nbsP     }                    public static void main (String[] args)  {               MultiThreadTest m = new  Multithreadtest ();              thread t1  = new thread (M, "Thread a");               thread t2 = new thread (M, "thread b");              t1.start ();               t2.start ();          }      }           class student {     &nbsp     int age;                public int getage ()  {               return age;          }                public void setage (int age)  {               this.age = age;           }                }    

All of the above 2 methods implement the same functionality, but the method is different

Threadlocal uses the situation mainly solves the inconsistency problem which the data data in the multithreading produces because of concurrency. Threadlocal provides a copy of the data that is concurrently accessed in each thread and runs the business by accessing the Vice, which results in memory savings that greatly reduce the performance consumption of thread synchronization and reduce the complexity of thread concurrency control.

Threadlocal cannot use atomic types, only object types are used. Threadlocal is much simpler to use than synchronized.

Both threadlocal and synchonized are used to resolve multithreaded concurrent access. But there is an essential difference between threadlocal and synchronized. Synchronized is the mechanism by which a variable or block of code can only be accessed by one thread at a time. The threadlocal provides a copy of the variable for each thread, so that each thread is not accessing the same object at a given time, isolating multiple threads from data sharing. Synchronized, in contrast, is used to gain data sharing when communicating between multiple threads.

synchronized is used for data sharing between threads, while threadlocal is used for data isolation between threads.

Of course, threadlocal does not replace synchronized, which handles different problem domains. Synchronized is used to implement synchronization mechanisms, more complex than threadlocal.

General steps for threadlocal use:

1, in the multithreaded class (such as the Threaddemo Class), create a Threadlocal object threadxxx, to save the thread between the object that needs to be quarantined processing xxx.
2, in the Threaddemo class, create a method to obtain the data to be quarantined getxxx (), in the method to judge, if the Threadlocal object is null, should be new () an object of the isolation access type, and cast to the type to be applied.
3, in the Threaddemo class of the Run () method, through the GetXXX () method to obtain the data to be manipulated, so as to ensure that each thread corresponds to a data object, at any time the operation of this object.

Come from:http://gcgmh.javaeye.com/blog/455940

Two. Principle of threadlocal:

[Java] View Plain Copy public class threadlocal      {      Private map values = collections.synchronizedmap (New hashmap ());       public object get ()       {      Thread  curthread = thread.currentthread ();       Object o =  values.get (Curthread);       if  (o == null &&  !values.containskey (curthread))       {      o =  initialvalue ();      values.put (Curthread, o);       }      return o;      }            Public void set (object newvalue) &NBSP;&NBSP;&Nbsp;   {      Values.put (Thread.CurrentThread (),  newValue);      }           Public object initialvalue ( )       {      return null;       }     }    

This shows that threadlocal a map to hold a copy of the variable for each thread. This map takes the current thread as key. Compared with synchronized, threadlocal is a strategy to change time in space to implement multithreaded programs.

Synchronized or threadlocal?
Threadlocal provides a very easy way to achieve multithreading in space in exchange for time. Because multiple threads have concurrent access without waiting, using threadlocal can result in greater performance. While using threadlocal can lead to more memory overhead, this overhead is negligible. Because objects that are stored in threadlocal are usually smaller objects. In addition, the atomic type cannot be used with threadlocal, only object type is used. Threadlocal is much simpler to use than synchronized.
Both threadlocal and synchonized are used to resolve multithreaded concurrent access. But there is an essential difference between threadlocal and synchronized. Synchronized is the mechanism by which a variable or block of code can only be accessed by one thread at a time. The threadlocal provides a copy of the variable for each thread, so that each thread is not accessing the same object at a given time, isolating multiple threads from data sharing. Synchronized, in contrast, is used to gain data sharing when communicating between multiple threads.
Synchronized is used for data sharing between threads, while threadlocal is used for data isolation between threads.
Of course, threadlocal does not replace synchronized, which handles different problem domains. Synchronized is used to implement synchronization mechanisms, more complex than threadlocal.

Come from:http://www.javaeye.com/topic/81936

http://www.javaeye.com/topic/103804

                     http://blog.csdn.net/yangairong1984/archive/2008/04/15/2294572.aspx

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.