Solving the problem of lazy thread safety in single-case design mode

Source: Internet
Author: User

First write a single example:

public class Singledemo {      private static singledemo s = null;      Private Singledemo () {} public      static  Singledemo getinstance () {          if (s = = null) {              s = new Singledemo ();          }          return s;      }  }  

  


Write a test class:

public class ThreadDemo3 {public            static void Main (string[] args) {          Singledemo S1 = singledemo.getinstance (); 
   singledemo s2 = singledemo.getinstance ();          SYSTEM.OUT.PRINTLN (s2 = = s2);}  }  

  

The running result is always true, stating that there is no problem with a single thread, and the following is a multi-thread access to the singleton

public class ThreadTest implements Runnable {      //Store singleton object, use Set to not hold duplicate element public      set<singledemo> Singles = New Hashset<singledemo> ();      @Override public      Void Run () {          //Get a singleton          singledemo s = singledemo.getinstance ();          Add a singleton          singles.add (s);      }  }  

  


Using multiple threads for concurrent access to a single example:

public class ThreadDemo3 {public static void main (string[] args) {//Singledemo S1 = Singledemo.getinst  Ance ();  Singledemo s2 = singledemo.getinstance ();          SYSTEM.OUT.PRINTLN (s2 = = s2);          ThreadTest t = new threadtest ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();      System.out.println (T.singles); }}//Cannot see the result changed to the following public class ThreadDemo3 {public static void main (string[] args) {//Singledemo S1 = S  Ingledemo.getinstance ();  Singledemo s2 = singledemo.getinstance ();          SYSTEM.OUT.PRINTLN (s2 = = s2);          ThreadTest t = new threadtest ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start (); New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();          New Thread (t). Start ();        try {thread.sleep;} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}      System.out.println (T.singles);   }  }

  

The results of the operation are as follows:

[[Email protected], [email protected]]

Or

[[email protected]]

Describes thread concurrency access security issues, not all of which are the same instance

How to solve the thread safety problem?

Of course, the sync lock mechanism is used.

Thread Safety Lazy

The following improvements to the single example:

 Public classSingledemo {Private StaticSingledemo s =NULL; PrivateSingledemo () {} Public Static synchronizedSingledemo getinstance () {if(s = =NULL) {s=NewSingledemo (); }          returns; }  }  


Thread safety resolves after adding a sync function

Run multiple times to get the same instance without 2 instances

[[email protected]]

However, in the case of multi-threaded concurrent access, each thread to obtain an instance to determine the lock, efficiency is low, in order to improve efficiency, I added a double-judge method, solve the problem of efficiency

The code is as follows;

Double check Lock

public class Singledemo {      private static singledemo s = null;      Private Singledemo () {} public      static  Singledemo getinstance () {/          * If the first thread obtains a singleton instance object,          * The subsequent thread does not need to enter the synchronization code block when retrieving the instance *          /if (s = = null) {              ///The lock used for the code block is a singleton bytecode file object and can only be used with this lock              synchronized ( Singledemo.class) {                  if (s = = null) {                      s = new Singledemo ();}}          }          return s;      }  }  

  


In this way to solve the lazy-type thread safety problems, but also improve efficiency, but in the actual development or use a hungry man-style comparison, after all, this code is more, more cumbersome. The following is a single case of the Great god http://www.hollischuang.com/archives/1373

Solving the problem of lazy thread safety in single-case design mode

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.