Search code examples
javasingletonlazy-initialization

Singleton lazy vs eager instantiation


If a singleton is implemented as follows,

class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }
}

How is this implementation different from the lazy initialization approach? In this case,the instance will be created when the class is loaded and the class itself is loaded only on the first active use (for example, Singleton.getInstance() not when you declare for instance Singleton singleton = null;)

Even with lazy initialization approach, the instance is created on the call to getInstance()

Am i missing something here?


Solution

  • You may call any other static methods or static member variable too to load the singleton instance.

    class Logger {     
       private static Logger instance = new Logger(); 
       public static String LOG_LINE_SEPERATOR =  
          System.getProperty("line.separator");
       public static Logger getInstance() {  
              return instance;     
       } 
    
       public static String logPattern() {
           return null;
       }
    } 
    

    ...

    Logger.LOG_LINE_SEPERATOR; // load Logger instance or
    Logger.logPattern(); // load Logger instance