Reputation: 2238
While going through this article I came across the below code which explained safe publication fields.
public class SafeLocalDCLFactory implements Factory {
private volatile Singleton instance;
@Override
public Singleton getInstance() {
Singleton res = instance;
if (res == null) {
synchronized (this) {
res = instance;
if (res == null) {
res = new Singleton();
instance = res;
}
}
}
return res;
}
}
My doubt is why do we need local var res
defined in the getInstance()
? Isn't the volatile
and DCL
enough to guarantee safe publication
? What exactly is the purpose of defining a local var res
here and then comparing it for null
?
EDIT : The article explains the below to justify the need to use local var. But how are we protecting ourselves from returning null?
The introduction of local variable here is a correctness fix, but only partial: there still no happens-before between publishing the Singleton instance, and reading of any of its fields. We are only protecting ourselves from returning "null" instead of Singleton instance
Upvotes: 0
Views: 34
Reputation: 51587
It minimizes the number of reads from the volatile variable instance
. Volatile variable access is more expensive than non-volatile memory access, because usually it involves a memory barrier. By assigning it to a temporary variable, this code reads from the volatile variable only once if it is already initialized, instead of twice (once to check, once to return).
Upvotes: 1