Singleton Pattern Example

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