我正在阅读有关从Effective Java. 该代码执行以下操作:
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;
}
它说 usingresult似乎不需要,但实际上确保field在它已经初始化的常见情况下只读取一次。
但我不明白这一点。和直接做有什么区别if(field == null)?我不明白为什么if (result == null)会有所不同,更不用说如上所述了。