In two previous posts I have tried to convince you not to implement the Singleton at all and to give up implementing it with lazy initialisation. Today I show how to write a singleton that uses lazy initialization. The presented code is one of 3 possible versions – the most readable one. Others will be shown in upcoming posts.
As with everything else in life there is a trade-off for the lazy initialization: either you loose the readability of the code or decrease the performance. Today we choose the latter one. Without further ado see the following snippet:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: |
public class Singleton {
private static Singleton INSTANCE = null;
// 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 synchronized Singleton getSingleton() {
if (INSTANCE == null) {
INSTANCE = createInstance();
}
return INSTANCE;
}
}
|
As you can see we finally have the lazy-initialization. Because we assume that our singleton can be accessed by many threads we need to synchronize the getSingleton(). You can see that the code is well readable, very similar to the one shown previously. So where is the performance impact?
The problem is in synchronization – unfortunately it’s not free. Notice that every time someone wants to get access to the singleton he has to wait on getSingleton() for other thread to exit. Even if no other thread is working the synchronization itself takes lots of time.
The only question remains: do you really care about that performance decrease? Not always – it depends on what your singleton does. If it handle heavy tasks (eg. query execution) or is not accessed very often than probably you won’t even notice. The only way this can hit you if the getSingleton() is executed heavily and the usage of the singleton is very short. That does not happen often in real life
To summarise: if you need lazy initialization there is a huge chance that the snippet shown above is exactly what you need. It is much better to have a readable code than try to optimize every irrelevant bit of your program. Still, if you’re 100% sure you need to have getSingleton() working fast then read one of the next posts where I will show you how to get it done (unfortunately by losing code readability).
6 Comments until now
You forgot to mention that even if instantiation is slow, after instantiation the monitor would almost always be locked on the “fast track” (optimistic no-locking with fallback) instead of the “slow track” (preemptive locking).
Also, if the singleton object can be instantiated multiple times without penalty, you could drop the synchronize altogether.
Ran’s optimizations aren’t available on older JVMs, like the Sun JDK5. I’ve seen noticible performance problems due to lazy singleton initialization. The locking can be avoided by using a static inner class as the instance holder, which relies on class-loading. Its fast, simple, and sadly not well known.
There are already a zillion articles dealing with singletons and lazy initialization. For the sake of S/N ratio on the Internet, please add something that is not already there:
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Five articles talking about singleton initialization seems like a bit too much.
The synchronization part is a popular trick that many developers, as I’ve seen, fall into.
But I do agree with Ran as well: “if the singleton object can be instantiated multiple times without penalty, you could drop the synchronize altogether”
@Ben: it’s very sad that you did not mention what you mean by using a static inner class as the instance holder. I’m one of the people who would like to know it.
@Mohamed
Sure, the following relies on the inner class being loaded separately. On load it creates the parent’s instance. This relies on classloading being a serial process, so synchronization is not needed. (Forgive formatting if it shows up poorly!)
public class Singleton {
private Singleton() {}
public Singleton getInstance() {
return Holder.INSTANCE;
}
private static final class Holder {
static final Singleton INSTANCE = 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!