Singleton pattern

Traditional simple way

 public class Singleton {
   private static final Singleton INSTANCE = new Singleton();
 
   // Private constructor prevents instantiation from other classes
   private Singleton() {}
 
   public static Singleton getInstance() {
      return INSTANCE;
   }
   public Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
   }
 }
 

Traditional simple way using synchronization

 public class Singleton {
   // volatile is needed so that multiple thread can reconcile the instance
   // semantics for volatile changed in Java 5.
   private volatile static Singleton singleton;
 
   private Singleton(){}
 
   // synchronized keyword has been removed from here
   public static Singleton getSingleton(){
     // needed because once there is singleton available no need to acquire
     // monitor again & again as it is costly
     if(singleton==null) {
       synchronized(Singleton.class){
          // this is needed if two threads are waiting at the monitor at the
          // time when singleton was getting instantiated
          if(singleton==null)
          singleton= new Singleton();
       }
    }
   return singleton;
  }
 
}
 

你可能感兴趣的:(thread)