tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Design Patterns > Java Design Patterns > Lazy Initialized Singleton

Lazy Initialized Singleton 

This example shows creating a Lazy singleton. Means the singleton instance creation is delayed until it is really required. This approach helps to improve application startup performance.

File Name  :  
com/bethecoder/tutorials/dp/singleton/lazy/LazySingleton.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.dp.singleton.lazy;

public class LazySingleton {

  private static LazySingleton instance = null;
  
  /**
   * Make sure to have private default constructor.
   * This avoids direct instantiation of class using 
   * new keyword/Class.newInstance() method
   */
  private LazySingleton() {
    init();
  }
  
  private void init() {
    //Initialization code 
  }
  
  /**
   * Make the 'getInstance' method as 'synchronized method'
   * to avoid two thread creating multiple instances 
   * of LazySingleton.
   
   @return
   */
  public static synchronized LazySingleton getInstance() {
    
    if (instance == null) {
      instance = new LazySingleton();
    }
    
    return instance;
  }
}
   

File Name  :  
com/bethecoder/tutorials/dp/singleton/lazy/Test.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.dp.singleton.lazy;

public class Test {
  
  public static void main (String [] args) {
    
    System.out.println(LazySingleton.getInstance());
    System.out.println(LazySingleton.getInstance());
    
  }
}
   

It gives the following output. Check the object hash code, its identical for all calls to LazySingleton.getInstance() method.
com.bethecoder.tutorials.dp.singleton.lazy.LazySingleton@25682568
com.bethecoder.tutorials.dp.singleton.lazy.LazySingleton@25682568


                    Print

   



Books Recommendation

 
 
bl  br