私有构造函数和实例 - 多项选择

use*_*723 3 java singleton

我正在尝试找出以下 MC 问题的答案。我尝试在谷歌上寻找答案,但人们似乎对这个问题有不同的答案。有人可以解释一下他们的答案吗?

public class Gingleton {
    private static Gingleton INSTANCE = null;

    public static Gingleton getInstance()
    {
        if ( INSTANCE == null )
        {
            INSTANCE = new Gingleton();
        }
        return INSTANCE;
    }

    private Gingleton() {
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 可以创建多个 Gingleton 实例(我的选择)

  • Gingleton 永远不会被创建

  • 构造函数是私有的,不能被调用

  • value 可以被垃圾回收,调用 getInstance 可能会返回垃圾数据

Mar*_*mro 5

新实例的创建getInstance()不会以任何方式同步,因此在多线程环境中可能会创建多个实例。为了确保只有一个实例,您应该这样做:

public class Gingleton {

    // volatile
    private static volatile Gingleton INSTANCE = null;

    public static Gingleton getInstance()
    {
        if ( INSTANCE == null )
        {
            synchronized (Gingleton.class) {  // Synchronized
                if ( INSTANCE == null )
                {
                    INSTANCE = new Gingleton();
                }
            }
        }
        return INSTANCE;
    }

    private Gingleton() {
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Rembo [易失性是上面示例有效的唯一原因。(读完这整件事,没有一点解释。)](http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html) (2认同)