为什么 Singleton 无法 运行?

Why does Singleton fail to run?

我正在尝试创建一个线程安全的单例。如果我删除 synchronized 函数并取消对条件的注释,程序将 运行 但它不是线程安全的,对吗? 我是 java 新手(也是使用线程的新手)。

class Singleton {
    volatile public static Singleton instance = null;
    private String someText;

    private Singleton() {
        this.someText = "Only one instance of this class can be created!";
    }

    public static Singleton getInstance() {

        synchronized (instance) {
            if(instance == null) {
                instance = new Singleton();
            }
        }

        // this will run
        // if (instance == null) {
        //  instance = new Singleton():
        // }

        return instance;
    }

    public String getSomeText() {
        return this.someText;
    }

    public void setSomeText(String text) {
        this.someText = text;
    }
}

public class Assignment1 {
    /*
        Assignment 1
        Implement a Singleton with double-checked locking.
    */

    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1.getSomeText());
        System.out.println(singleton2.getSomeText());
        singleton1.setSomeText("Here's our new text!");
        System.out.println(singleton1.getSomeText());
        System.out.println(singleton2.getSomeText());
    }
}

第一次执行getInstance()时,instancenull。您无法在 null 对象上同步。解决方案是在 class 本身上同步。

试试这个:

   public static Singleton getInstance() {

        synchronized (Singleton.class) {
            if(instance == null) {
                instance = new Singleton();
            }
        }    
    }

我建议添加额外的检查以防止锁定,以防 instance 不是 null:

  if (instance == null) {
        synchronized (Singleton.class) {
            if (instance == null) {
                instance = new Singleton();
            }
        }
    }