MULTITHREADED SINGLETON JAVA CLASS
First We see a Simple Singleton Class Here :
Here we are doing the Lazy Loading .
class Singleton {
private static Singleton instance;
private Singleton(){};
public static Singleton getInstance(){
if(instance== null)
instance = new Singleton();
return instance;
}
}
The Main Properties of a Singelton Class is below :-
1. There should always be a single instance of a class in an Application.
2. We can't be able to instantiate the class using the using the new keyword.
3. We can get the instance of the class using a getter method.
The Above Code looks fine as we have made our constructor and creating the instance for the first time and reusing it whenever asked .
Now , the problem arises when two parallel threads try to access the method , what happens then :
Both the threads will create one instance for the class hence breaking the singelton pattern .
How to tackle it :-
A simple way could be this .
private static Singleton instance;
private Singleton(){};
public synchronized static Singleton getInstance(){
if(instance== null)
instance = new Singleton();
return instance;
}
We can use the synchronized keyword here in the method :
This will make our method a critical section , which does not allow multiple threads to access it at once .
A better approach here could be using a Synchronization block instead of Synchronization method : -
As Synchronization block provides more granular control unlike synchronization method which provide a generic control .
class Singleton {
private static Singleton instance;
private Singleton(){};
public static Singleton getInstance(){
if(instance == null) {
synchronized(Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
This is a better solution to solve the multithreading issue in singelton pattern.
This pattern can still be broke by
1. Reflection
2. Serialization
3. Cloneability
P.S :-
Please Follow for more Insights in Java backend Development
https://twitter.com/JavaUnlocked
Will cover the above three in next article.