In: Computer Science
Explain how multithreading can complicate the implementation of the singleton pattern and explain how to resolve this complication.
The singleton pattern is a simple pattern i.e.it is a software design pattern that restricts the instantiation of a class to one single instance i.e. the purpose of the singleton class is to control object creation, limiting the number of objects to only one. The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.
How multithreading complicates singleton pattern :-
The complication with the multithread while implementing singleton pattern is that two threads might get ahold of two different instances if they enter at same time in the getInstance method.
Example :-
public class Singleton {
/** The unique instance **/
private static Singleton instance;
/** The private constructor **/
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Here the getInstance method is not synchronize this causes complications as two thread get ahold if enters at same time.
How to overcome :-
To overcome this complication we have to make the getInstance method synchronize i.e.
public class Singleton {
/** The unique instance **/
private static Singleton instance;
/** The private constructor **/
private Singleton() {
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Now, the getInstance method is synchronized so we force every threads to wait its turn before it can enter the method. Synchronized block allows only one thread to run at a time .
So, the synchronization of getInstance method helps to overcome the complication related to multithreading while implementing singleton pattern.
Thumps up!