the synchronized keyword already supports the happen-before rules , so why do we still need to use volatile on the filed .
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;
}
}
https://docs.oracle.com/javase/specs/jls/se21/html/jls-17.html#jls-17.4.5
enter image description here
there are several ways to support happen-before rules ,such as using volatile , synchronized keyword . in the double-checked locking pattern for Singletons , we don’t need to
use both methods to ensure the happen-before rule is followed .
jerry davis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.