In Item 71 in ‘Effective Java, Second Edition’ the Double-check idiom and the single-check idiom are introduced for lazily instantiating 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;
}
In the double-check idiom Joshua states, that the result variable is used to make sure that the volatile field is only read once, which improves performance. This I understand, however I don’t see why we need it in the single-check idiom, since we only read field once anyway.
In the single-check idiom, without the result variable you’d still be reading it twice; once for the null check and once for the return value.