In one of the recent posts I was trying to convince everyone not to create singletons. For those who still are not convinced I show today how to write it in a simplest and safest way possible. The following code base on one assumption: you do not need lazy initialization.
The idea behind lazy initialization is that the creation of the singleton object may be expensive and therefore we want to perform it only if we are about to use the singleton. This way we can save some time (assuming that in a given run singleton is not used) and memory (we keep some free mem before the first usage). But then the question arises: how often do you need that?
In my experience most of the singletons are either small objects that we expect to use often and therefore want to save memory by having only one instance of it (like ‘empty node’ or enum values) or large objects managing system resources (connection pool, database access) that are used very often in the code. In both of those cases you do not really benefit from lazy initialization.
Why am I convincing you to drop lazy initialization? Because in 95% of examples it is used only because the programmer wanted his code to look more fancy (pattern fever!). Without it the singleton code is really simple and really safe. (By safe I mean mostly coder-safe: that only a drunk junior developer could get the idea to ‘fix it’ and introduce something nasty). The code is following:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: |
public class Singleton {
private static final Singleton INSTANCE = createInstance();
// Remember that Singleton constructor should be private
private Singleton() {}
private static Singleton createInstance() {
Singleton singleton = new Singleton();
//Initialization of the singleton here
return singleton;
}
public static Singleton getSingleton() {
return INSTANCE;
}
}
|
Obviously we assume that any instance method of Singleton is properly synchronized and that it does not have a user-visible state. Some things to notice in this snippet:
- It is important to have the constructor private – otherwise users of the class may start ignoring your getSingleton() and start creating the singletons on their own.
- The reference INSTANCE to the singleton object is final. Thanks to that you have the guarantee that no one will swap this instance with for example a test one.
- Because the getSingleton() just returns a constant reference it is thread safe and you do not have to synchronize it.
The code above is the easiest possible implementation. For those who still insist on using lazy initialization in one of the next posts I will show another way of implementing singleton pattern to include that.
7 Comments until now
>I show today how to write it in a simplest and safest way possible
Actually, this is the simplest and safest way possible:
enum Singleton { INSTANCE }
The enum implementation certainly is the simplest, and if your singleton is also serializable, then unless you provide a readResolve() implementation, it’s also the only way to guarantee that it forever remains a singleton (see Item #3 of Bloch’s Effective Java).
Yes, I know Bloch’s opinion about that but I do not agree with him because of several things:
- with enum your singleton cannot extend any other class (you can only implement interfaces)
- your singleton object is exactly of the enum class that contains it (you cannot separate the class that gives you access to singleton with the singleton class)
- your singleton is of type Enum and because of that it has many useless and confusing methods (oridinal(), name()…)
- you do not control access to the singleton by a get/access method (see the comments about benefits from method like that in Effective Java #1)
The only gain of doing this with enum is the serialization issue… but if you do need that I would strongly suggest dealing with readResolve() as it is more readable what kind of issue you are solving this way.
Simpler is to have the INSTANCE public:
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
// Remember that Singleton constructor should be private
private Singleton() {}
}
It is simpler, but you lose the advantage of having control over the way the singleton is accessed. With a get method it will be easier to incorporate future changes – what if you change your mind and want to have a lazy initialization? Maybe want to add logging on every get / count the numbers of gets? Maybe at some point you will want to drop the singleton quality and just give new objects every time someone request one? Without a access method you do not have those possibilities…
@ PPOW: I thought Josh Bloch’s suggestion was not
enum Singleton { INSTANCE }
but
private static Singleton createInstance() {
return EnumSet.of ( new Singleton() );
}
Women’s vibram five fingers kso shoes Gray Pink Shoes can keep your feet in the freest condition,just as if your were barefooted. vibram five fingers kso shoes is made of the best and proper materials,so you don’t need to doubt of its comfort with so thin sole and upper.
Gray match with a dreamlike and romantic color,pink vibram five fingers kso shoes is very consistent with the style of young girls.In this busy and tense times,people need relax without any fetter.
Add your Comment!