Singleton Pattern #2: Lazy vs Eager Instantiation for a Singleton Class

This post is in continuation to my previous post where I discussed about basics of singleton pattern. The kind of instantiation mentioned in that post, where we create an instance of singleton class only when it is called for the first time is called lazy instantiation. Another variation can be creating the instance before it is called, this kind of instantiation is called eager instantiation

Public Class singletonExample {
private static singletonExample instance=new singletonExample();
private singletonExample{
// no instantiation is possible
}

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

If you look carefully, here we are using

private static singletonExample instance=new singletonExample();

to initialize the object ‘instance’ rather than setting it as null initially. And in our getInstance() method we are just returning the ‘instance’ without any checks. So the advantage in this case is that we are saved making one check everytime getinstance is called. One apparent disadvantage is that in this case the instance of singletonExample will always be present whether it is called or not.

Originally posted February 13, 2007

Brought back using archive.org