I am reading about double check locking from Effective Java
. The code does the following:
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) { // First check (no locking)
synchronized(this) {
result = field;
if (result == null) // Second check (with locking)
field = result = computeFieldValue();
}
}
return result;
}
It says that using result
seems unneeded but actually ensures that the field
is only read only once in the common case where it is already initialized.
But I don't understand this. What is the difference with doing if(field == null)
directly? I don't understand why if (result == null)
is different, let alone better as stated.