为什么在双重检查锁定中使用 volatile [英] Why is volatile used in double checked locking

查看:31
本文介绍了为什么在双重检查锁定中使用 volatile的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

From Head First design patterns book, the singleton pattern with double checked locking has been implemented as below:

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

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

I don't understand why volatile is being used. Doesn't volatile usage defeat the purpose of using double checked locking i.e performance?

推荐答案

理解为什么需要 volatile 的一个很好的资源来自 JCIP 书.维基百科对该材料也有体面的解释.

A good resource for understanding why volatile is needed comes from the JCIP book. Wikipedia has a decent explanation of that material as well.

真正的问题是线程A可能会在instance构建完成之前为instance分配内存空间.Thread B 将看到该分配并尝试使用它.这会导致 Thread B 失败,因为它使用的是 instance 的部分构造版本.

The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. This results in Thread B failing because it is using a partially constructed version of instance.

这篇关于为什么在双重检查锁定中使用 volatile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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