- 对静态域使用延迟初始化
public class FieldType{
private static class FieldHolder{
static final FieldType field = computeFieldValue();
}
static FieldType getField(){
return FieldHolder.field;
}
}
- 对实例域使用延迟初始化
public class FieldType{
private volatile FieldType field;
FieldType getField(){
FieldType result = field;
if (result == null){
synchronized (this){
result = field;
if (result == null){
field = result = computeFieldValue();
}
}
}
return result;
}
}