我遇到过一些代码,其中开发人员不断使用嵌套 if 检查单例是否为 null 两次 - 如下面的代码所示:
private static processManager singleton = null;
...
public synchronized static processManager getInsatnce() throws Exception {
if(singleton == null) {
if(singleton == null){
singleton = new processManager();
}
}
return singleton
}
我看不出有什么原因会这样,但是代码中有很多实例,所以我认为可能有原因吗?
最佳答案
您的代码没有正确说明情况。这源于 double-checked 成语,它确实有意义:
// Double-check idiom for lazy initialization of instance fields.
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;
}
了解它 over here .
请注意,此习语仅适用于实例 字段。在你的问题中,你有一个 static
字段,对于这种情况,一个更简单的成语是主要选择:lazy initialion holder class 成语:
// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
static final FieldType field = computeFieldValue();
}
static FieldType getField() { return FieldHolder.field; }
关于Java - 是否有任何理由两次检查单例是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15498654/