On lazy vs eager initialization
The if
statement is an implementation of the lazy initialization technique.
A more explicit version is as follows:
private boolean firstTime = true;
private Stuff stuff;
public Stuff gimmeStuff() {
if (firstTime) {
firstTime = false;
stuff = new Stuff();
}
return stuff;
}
What happens is that the very first time gimmeStuff()
is invoked, firstTime
would be true
, so stuff
would be initialized to new Stuff()
. On subsequent invokations, firstTime
would be false
, so new Stuff()
would no longer be called.
Thus, stuff
is initialized "lazily". It's not actually initialized until the very first time it's needed.
See also
On thread safety
It needs to be said that the snippet is not thread-safe. If there are multiple threads, then in some race conditions new SingletonObjectDemo()
may be invoked several times.
One solution is to make synchronized getSingletonObject()
method. This does, however, have a synchronization overhead on ALL calls to getSingletonObject()
. The so-called double-checked locking idiom is then used to try to remedy this, but in Java, this idiom does not actually work until J2SE 5.0 with the introduction of volatile
keyword in the new memory model.
Needless to say that proper enforcement of singleton pattern isn't a trivial thing.
See also
Related questions
Effective Java 2nd Edition
Here's what the book has to say on these subjects:
Item 71: Use lazy initialization judiciously
As is the case for most optimizations, the best advice for lazy initialization is "don't do it unless you need to". Lazy initialization is a double-edged sword. It decreases the cost of initializing a class or creating an instance, at the expense of increasing the cost of accessing a lazily initialized field. Depending on what fraction of lazily initialized fields eventually require initialization, how expensive it is to initialize them, and how often each field is accessed, lazy initialization (like many "optimizations" actually harm performance).
In the presence of multiple threads, lazy initialization is tricky. If two or more threads share a lazily initialized field, it is critical that some form of synchronization be employed, or severe bugs can result.
Under most circumstances, normal initialization is preferable to lazy initialization.
Item 3: Enforce the singleton property with a private constructor or an enum
type
As of release 1.5. there is a third approach to implementing singletons. Simply make an enum type with one element. [...] This approach is functionally equivalent to the public
field approach, except that it's more concise, provides the serialization mechanism for free, and provides ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection-based attacks.
[...] A single-element enum type is the best way to implement a singleton.
Related questions
On enum
singleton/Java implementation:
On singleton pattern merits and alternatives: