Double Locking in Singleton Pattern in Java
In one of earlier posts, we learned Singleton design pattern in java & Singleton Design Pattern Without Cloning Java.
There is one more issue in this block of code that will come up in a multithreaded environment. In the below code, Thread.sleep is explicitly used in order to test the violation in multithreaded environment
Consider above code, where a method will be called in a multithreaded environment and so multiple threads enter the block and creates multiple instances which will violate the principal of Singleton Design Pattern as shown below :
To avoid so, we need to perform a double locking to ensure no 2 objects are created in multithreading environment as shown below:
In the above implementation we are synchronizing the static method which is a lock on an Class object. This will ensure only one thread will enter the synchronize method
Labels: Design patterns