I can't understand piece of code in Item 71 in 'Effective Java' about the Double-check idiom and the single-check idiom for lazy initialization of instance fields:
Double-check idiom
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) {
synchronized(this) {
result == field;
if (result == null)
field = result = computeFieldValue();
}
}
return result;
}
Single-check idiom
private volatile FieldType field;
FieldType getField() {
FieldType result = field;
if (result == null) {
field = result = computeFieldValue();
}
return result;
}
We use locking in first case, as i understand, in order to compute FieldValue()
performed atomically. But why we omit it in second case? Because now some alien thread could corrupt some value that take part in computation. What i missed?