Singleton class can have only one object in an entire application.
In this implementation, I use a function to create an object and I use synchronization to restrict entry of more than one thread into the block that creates the instance.
I double check forĀ null status of the object, to prevent creation of multiple instances of a singleton class.
public static Singleton instance(){ if(null == singleton) { synchronized(Singleton.class){ if(null == singleton) singleton = new Singleton(); } } return singleton; }
We check for null status before getting inside the synchronized block, to see if the instance is created or not.
Once, we get inside the synchronized block, we check for null status again, it is possible that the thread which was inside the block before current thread must have created an instance.
public final class Singleton{ //This code will create an object on the class load.. which is not needed // and it is not efficient //private static final Singleton singleton = new Singleton(); private static Singleton singleton; private Singleton(){} // Threads will wait in a queue to read the instance object. //Although, the instance has been already created //public static synchronized Singleton instance(){ public static Singleton instance(){ if(null == singleton) { synchronized(Singleton.class){ if(null == singleton) singleton = new Singleton(); } } return singleton; } }