为什么在双重锁定的这个例子中使用volatile [英] Why is volatile used in this example of double checked locking

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

问题描述

  public class Singleton {
private volatile静态单例实例;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if( instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}

我不明白为什么 volatile 正在使用。 volatile 使用失败了使用双重锁定的目的,即性能?

解决方案

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



真正的问题是,线程A 可以在构建实例之前分配一个内存空间实例线程B 将看到该作业并尝试使用它。这导致 Thread B 失败,因为它使用部分构造的实例


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

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

解决方案

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

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天全站免登陆