In most places, this is the implementation followed for Singleton Design Pattern.
It makes use of the keyword volatile
to prevent the issue of partial object creation (establishes happens-before relation between reads and writes to instance
).
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;
}
}
I was wondering if we could avoid the usage of volatile by making the entire getInstance()
method synchronized? If it does not work, how would the execution of both cases differ?
Soumya Sen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.