Java - 有没有理由检查单例是否为null两次? [英] Java - is there any reason to check if a singleton is null twice?

查看:83
本文介绍了Java - 有没有理由检查单例是否为null两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些代码,其中开发人员不断检查singleton是否为null两次使用嵌套if - 如下面的代码:

I have come across some code, where the developer is constantly checking if the singleton is null twice with a nested if - like in the code below:

private static processManager singleton = null;

...

public synchronized static processManager getInsatnce() throws Exception {

    if(singleton == null) {
      if(singleton == null){
             singleton = new processManager();
       }
     }
     return singleton
}

我看不出任何原因,为什么这可能是,但在代码中有许多实例,所以认为可能有一个原因?

I cannot see any reason why this might be, but there are numerous instances in the code, so thought there might be a reason?

推荐答案

p>您的代码无法正确显示此案例。这源于双重检查成语,其中有意义:

Your code doesn't demonstrate the case properly. This stems from the double-checked idiom, where it does make sense:

// 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;
}

阅读它在这里

注意这个成语是仅用于实例字段的不错选择。在你的问题中有一个 static 字段,对于这种情况下,一个更简单的成语是主要的选择:懒惰初始化持有者类 idiom: p>

Be careful to note that this idiom is a good choice only for instance fields. In your question you have a static field, for which case a much simpler idiom is the primary choice: the lazy initialion holder class idiom:

// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
    static final FieldType field = computeFieldValue();
}
static FieldType getField() { return FieldHolder.field; }

这篇关于Java - 有没有理由检查单例是否为null两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆