How to create thread-safe singleton objects in Java without using ‘synchronized’?
Answered
How to create thread-safe singleton objects in Java without using ‘synchronized’?
Best answer
Thread-safe singleton class can be created using inner static class approach.
public class Singleton { private Singleton() { } private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance(){ return SingletonHolder.INSTANCE; } }
Here the private static inner class contains the instance of the Singleton class. When the Singleton class is loaded, SingletonHolder class is not loaded into memory. SingletonHolder class gets loaded on first invocation of the getInstance method and creates the Singleton class instance. Java Language Specification guarantees the class initialization process to be serial (non-concurrent) so no synchronization is required in the getInstance method. This solution guarantees single instance and achieves better performance than using synchronized keyword.