I was exploring the singleton design pattern, I have developed a class...
public class SingletonObject {
private static SingletonObject ref;
private SingletonObject () { //private constructor
}
public static synchronized SingletonObject getSingletonObject() {
if (ref == null)
ref = new SingletonObject();
return ref;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException ();
}
}
but synchronization is very costly , so I move to new design of eagerly created instance rather than a lazily created one..
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return uniqueInstance;
}
}
But please advise me how the second design is advantage over the previous design..!!
Josh Bloch recommends using an enum:
public enum Foo {
INSTANCE;
}
For an explanation, see his Effective Java Reloaded talk at Google I/O 2008.
In summary:
"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."
As you stated, the second solution avoids synchronization costs. It is also simpler and cleaner, so easier to read and maintain. It has a little problem though: you miss a final
qualifier for private static Singleton uniqueInstance
, which means that it may not be guaranteed to be thread safe in a concurrent environment (although in this concrete case I don't think this would cause any tangible problem in real life... but better be on the safe side regarding thread safety). Luckily this is easy to fix.
Its other drawback is that as soon as the class Singleton
is referenced, the singleton object is created, even if it is never actually used. This might be a problem if creation is costly. It can be avoided with the Initialization-on-demand Holder idiom.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With