Singleton.java
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
In a Multi-threaded Environment
- Two Threads, Thread A and Thread B tries to access Object of Singleton class
- Thread A and B does call to Static getInstance() method
- Now when Thread A tries to do Null Check of instance instance == null chances of Thread B also entered the if block exists
. . . if (instance == null) { //Two threads may have passed the condition and might have got in instance = new Singleton(); } . . .
- Now both the Threads have their own instance for the Singleton class.
- So there would be 2 instances of Singleton class at the end of if Block
Now there are many work arounds but DoubleCheckedLocking, Enum Singleton and Initialization On Demand Holder are the Optimized approach
Refer Table in Link
Method 1
In this method we does static block initialization of Singleton along with synchronized getInstance() method which allows the access to only one thread at a point of time.
Singleton.java
public class Singleton { private static Singleton instance; private Singleton() {} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
But the above method is expensive since there is unnecessary locking and unlocking done every time the object get accessed.
Method 2(Double Checked Locking Singleton)
Instead of synchronizing the whole method lets synchronize the block of code which allows single thread to access the instance during the first time access.The consecutive thread would be served with the same thread allocated for the First thread once it is done with its task.
Singleton.java
public class Singleton { private volatile static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
Other ways of achieving singleton are by using Eager Initialization and ENUM which has its own advantages and disadvantages.