My question is that when we call getInstance() in singleton for the first time,then all its static properties are loaded in memory, i.e. before that it is not loaded in memory, so actually checking being null in the getInstance method is practically pointless and practically no different from the eager method, so why do we use this?
//lazy
class Singleton{
private static Singleton singleton;
private Singleton(){}
public Singleton getInstance(){
if (singleton==null) // this two lines
singleton=new Singleton(); // are useless I think
return singleton;
}
}
//eager
class Singleton{
private static Singleton singleton=new Singleton(); //before calling the getInstance()
//the singleton is not initialized so inline initializing is not a problem
private Singleton(){}
public Singleton getInstance(){
return singleton;
}
}
CodePudding user response:
Lazy initialization is required when construction of the Singleton
instance is a heavy operation consuming time and/or other resources, then it allows to postpone creation of the instance until it is really needed.
Another implementation option is to use a lazy holder class:
class Singleton{
private Singleton(){}
public Singleton getInstance(){
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
static final Singleton INSTANCE = new Singleton();
}
}
CodePudding user response:
Thanks to @Nowhere Man but I think this is my answer: according to this link In the third case, it is written in the answer that
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:3rd: A static field declared by T is assigned
and it is the same in the eager method in the singleton. We created a static object from the singleton class and initialized it, so the constructor of this class is called immediately, and it's not time to getInstance() anymore.