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.
Lazy initialization using single check idiom
-
11-12-2021 - |
Question
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.
Solution
OTHER TIPS
I prefer the following implementation of lazy evaluation:
@ThreadSafe
class MyClass {
private static class MyClassHelper {
public static final MyClass helper = new MyClass();
}
public static MyClass getInstance() {
return MyClassHelper.helper;
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow