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

查看:100
本文介绍了为什么在双重检查锁定中使用了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?

推荐答案

JCIP 是了解为什么需要volatile的一个很好的资源. >书. Wikipedia也对该材料进行了体面的解释.

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

真正的问题是Thread 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天全站免登陆