相关疑难解决方法(0)

为什么在双重检查锁定中使用volatile

Head First设计模式书中,具有双重检查锁定的单例模式已实现如下:

public class Singleton {
    private volatile static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

我不明白为什么volatile被使用.volatile使用不会 破坏使用双重检查锁定的目的,即性能?

java singleton design-patterns locking double-checked-locking

70
推荐指数
3
解决办法
2万
查看次数