Domanda

I am not quite clear on what is meant by the term Early initialization of a Singleton class. Also it would be helpful to understand the life cycle of a Singleton class.

È stato utile?

Soluzione

Well Lazy initialization means that you do not initialize objects until the first time they are used.

Early initialization is just reverse, you initialize a singleton upfront at the time of class loading.

There are ways to do early initialization, one is by declaring your singleton as static.

Following as an example:

public class SingletonClassEarly {
    private static SingletonClassEarly sce = new SingletonClassEarly();
    private SingletonClassEarly() {} // make it private

    public static SingletonClassEarly getInstance() {
        return sce;
    }
}

As per the lifecycle this singleton is loaded after JVM starts up and when class is initialized. It gets unloaded by JVM when shutting down/exiting.

Altri suggerimenti

Lazy Initalizaion

 class SingletonClass {

     private static SingletonClass object;
     private SingletonClass () {} 
     public static SingletonClass getInstance(){
        if(object == null){
            object= new SingletonClass (); //Lazy Initalizaion 
        }
        return object;
    }
 }

Early initialization

  class SingletonClass {

     private static SingletonClass object = new SingletonClass (); //Early initialization
     private SingletonClass () {} 

     public static SingletonClass getInstance(){
        return object;
    }
 }

A normally in Singleton this is what you see

 private static YouClass  singleTon ;

--

--

    public static YouClass getInstance(){
            if(singleTon  == null){
                singleTon  = new YouClass();
            }
            return singleTon  ;
        }

In this scenario, when you called getInstance() first time then only YouClass instance get created.

Early initialization, That means

In a your class

  private static YouClass singleTon = new YouClass();

Creating instance while declaring it self.

From Singleton pattern wiki ,read the types,

  • Lazy initialization

  • Eager initialization

  • Static block initialization

Thanks everyone for the explanation. That helps answer my question.

I also found a couple of useful blog posts which goes in more detail about how different approaches work.

Here are the links:

http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/

The next article helps explain the use of volatile keyword when using the double checked approach:

http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top