Initialize-On-Demand idiom vs simple static initializer in Singleton implementation
Is the Initialize-On-Demand idiom really necessary when implementing a thread safe singleton using static initialization, or would a simple static declaration of the instance suffice?
Simple declaration of instance as static field:
class Singleton
{
private static Singleton instance=new Singleton();
private Singleton () {..}
public static Singleton getInstance()
{
re开发者_运维问答turn instance;
}
}
vs
class Singleton {
static class SingletonHolder {
static final Singleton INSTANCE = new Singleton();
}
private Singleton () {..}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
I ask this because Brian Goetz recommends the 1st approach in this article:
http://www.ibm.com/developerworks/java/library/j-dcl/index.html
while he suggests the latter in this article
http://www.ibm.com/developerworks/library/j-jtp03304/
Does the latter approach provide any benefits that the former doesn't?
Well what i can say These articles are 7-9 years old.
Now we have > Java 1.5 where we have power of enumeration enum
. According to 'Josh Block' The best way to write a singleton is to write a Single Element enum
public enum MySingleton{
Singleton;
// rest of the implementation.
// ....
}
But for your question I guess there is no issue in using either of the implementations. I personaly prefer the first option because its straightforward, simple to understand.
But watch out for the loop holes that we can be able to create more objects of these class in the same JVM at the same time by serializing and deserializing the object or by making the clone of the object.
Also make the class final, because we can violate the singleton by extending the class.
In first approach your singleton will get created once you load Singleton
class. In the other, it will get created once you call getInstance()
method. Singleton
class may have many reasons to get loaded before you call getInstance
. So you will most likely initialize it much earlier when you actually use it and that defeats the purpose of lazy initialization. Whether you need lazy initialization is a separate story.
The simple declaration pattern constructs the singleton when when the class Singleton is loaded. The initialize-on-demand idiom constructs the singleton when Singeton.getInstance() is called -- i.e., when class SingetonHolder is loaded.
So these are the same except for time; the second option allows you delay initialization. When to choose one or the other depends on (among other things) how much work you are doing in Singleton's constructor. If it's a lot, you may see improved application startup time with initialization-on-demand.
That said, my advice is to try not to do too much there so that the simplest pattern works for you.
-dg
精彩评论