Tuesday 19 April 2016

Effective Java Item 71: Lazy initialization, holder class, double checking

static field uses holder class

 private static class ValueHolder{  
     static final String value = "Lazy initialized";  
   }  
   
   public static String getValue(){  
     return ValueHolder.value;  
   }  

instance field uses double check

 private volatile String value;  
   
   public String getValue(){  
     String result = value;  
     if (result == null){  
       synchronized (this){  
         result = value;  
         if (result == null){  
           value = result = "LazyInitialized";  
         }  
       }  
     }  
     return result;  
   }  

if you don't mind re-creating instance again, You can use single check

 public String getValue(){  
     String result = value;  
     if (result == null){  
       value = result = "LazyInitialized";  
     }  
     return result;  
   }