Everybody know how to write thread-safe singleton.
Consider standard approach:
public class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }
The example above could be slow – consider synchronization cost every time you getting singleton instance.
Can you do it faster? Of course:
public class FasterSingleton { private static volatile FasterSingleton instance; private FasterSingleton() {} public static FasterSingleton getInstance() { // no need for synchronization // on this place: if(instance == null) { // just in case: // synchronize on the *.class object: synchronized(FasterSingleton.class) { if(instance == null) { instance = new FasterSingleton(); } } } return instance; } }
The synchronization cost is much lower – you have it only if you didn’t have initialized the object. On the rest of getInstance() invocations you only checks that instance != null and returning object.
Maybe you will be amazed – but there is another – the fastest option.
The thing you have to use is static field initialization. Let’s see the trick:
public class TheFastestSingleton { // static fields are initialized only once // when using class for first time! private static TheFastestSingleton instance = new TheFastestSingleton(); private TheFastestSingleton() {} public static TheFastestSingleton getInstance() { return instance; } }
As you see we don’t need no synchronization and got thread-safe singleton. It’s the fastest implementation of singleton you can do in Java, but if you think you know faster way – please post it in comments :).
The source of the evil in the programming world is premature optimization. You should optimize only when the profiler tells you what is a bottleneck.
Singletons in Java should be implemented with a one element enum. It’s the best way.
Well, enum way is too hacky for me, so for me better solutions are showed above in the article. If you show your reasons we can discuss it.
Wouldn’t call it hacky. It’s the purest singleton in Java. And you get serializability out of the box if you need it – you don’t mess with readObject, etc. Joshua Bloch The Guru says so. ;-)
Didn’t think about serialization. See that looks pure, but as I have written a lot of code in C enum will be always kept in my mind as a vector of values (I don’t like writing lots of logic in Java enums).
The other thing is – The Guru cannot be wrong ;)
Nice post , just to add
While writing Singleton class we need to consider following points also :
1) Lazy initialization
2) Early initialization
3) Serialization
4) Many ClassLoaders
5) Cloning
Thanks
Javin