Reputation: 41
In Java singleton, most people told us we need volatile to prevent instruction reordering, but someone told me it no longer needs volatile in high version JDK, is he right? If so, why?
public class SafeDCLFactory {
private volatile Singleton instance;
public Singleton get() {
if (instance == null) { // check 1
synchronized(this) {
if (instance == null) { // check 2
instance = new Singleton();
}
}
}
return instance;
}
}
Upvotes: 3
Views: 149
Reputation: 718788
Does singleton double-checked locking still need volatile in high version JDK (e.g. jdk11 or jdk14)?
Yes it does. All versions of Java from Java 5 onwards require instance
to be volatile
.
(Prior to Java 5 the above code did not work reliably, whether instance
was declared as volatile
or not.)
... someone told me it no longer needs volatile ...
I would challenge that "someone" to provide a credible source (or a "happens-before" proof) to back up their assertion. If they are correct, all the information they need to construct a proof is in JLS 17.4 ... for the relevant Java version.
Upvotes: 5