Singleton (lazy man and starving the formula) and Optimization

Example handwriting single (starving formula)

. 1  class SingleObj {
 2      // private variables 
. 3      Private  static SingleObj SINGLE = new new SingleObj ();          
 . 4     // private constructor can not be instantiated   
. 5      Private  static SingleObj () {}
 . 6  
. 7      public  static SingleObj the getInstance () {
 . 8      return SINGLE ;    
 9    }      
 10 }

Advantages: no lock, higher efficiency

Disadvantages: initialized when the class is loaded, wasting memory

 

 

Lazy style

 1 class Singleton{
 2       private static Singleton single;
 3       
 4       private static Singleton(){}
 5 
 6      public static synchronized Singleton getInstance(){
 7         if(single==null)
 8             single =new Singleton();
 9         return single;
10     }
11 }             
View Code

Pros: The first call was initialized, to avoid wasting memory

Disadvantages: low efficiency lock

 

Guess you like

Origin www.cnblogs.com/tony-zhu/p/11504764.html