I read about blocking double check out Effective Java.
The code performs the following actions:
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) {
synchronized(this) {
result = field;
if (result == null)
field = result = computeFieldValue();
}
}
return result;
}
It says that use resultseems unnecessary, but actually ensures that it fieldis read only once in the normal case, when it is already initialized.
But I don’t get it. What is the difference with executing if(field == null)directly?
I do not understand why it if (result == null)is different, not to mention the best, as indicated.
Any help understand this please?
source
share