I just got to read the following code somewhere :
public class SingletonObjectDemo {
private static SingletonObjectDemo singletonObject;
// Note that the constructor is private
private SingletonObjectDemo() {
// Optional Code
}
public static SingletonObjectDemo getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonObjectDemo();
}
return singletonObject;
}
}
I need to know what is the need of this part :
if (singletonObject == null) {
singletonObject = new SingletonObjectDemo();
}
What if we do not use this part of code ? There would still be a single copy of SingletonObjectDemo, why do we need this code then ?
This class has a field
SingletonObjectDemo singletonObjectthat holds the singleton instance. Now there are two possible strategies –1 – You do eager initialization of the object with the declaration –
This will cause your singleton object to be initialized the moment the class is loaded. The downside of this strategy is that if you have many singletons, they will all be initialized and occupying memory even when they are not needed yet.
2 – You do lazy initialization of the object i.e. initialize it when the first call to
getSingletonObject()is made –…
This saves you the memory until the singleton is really needed. The downside of this strategy is that the first invocation of the method may see slightly worse response time as it will have to initialize the obejct before returning it.