双重检查锁定物品 [英] Double checked locking Article

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

问题描述

我正在阅读这篇文章关于检查锁定并且超出了文章的主题我想知道为什么在文章的某些方面作者使用下一个成语:

I was reading this article about "Double-Checked locking" and out of the main topic of the article I was wondering why at some point of the article the author uses the next Idiom:


清单7.尝试解决无序写入问题

Listing 7. Attempting to solve the out-of-order write problem

public static Singleton getInstance()  
{
    if (instance == null)
    {
        synchronized(Singleton.class) {      //1
            Singleton inst = instance;         //2
            if (inst == null)
            {
                synchronized(Singleton.class) {  //3
                    inst = new Singleton();        //4
                }
                instance = inst;                 //5
            }
        }
    }
    return instance;
}


我的问题是:
有没有理由将两次代码同步锁定一次?
这有什么用途吗?

And my question is: Is there any reason to synchronize twice some code with the same lock? Have this any purpose it?

非常感谢提前。

推荐答案

锁定两次的目的是尝试以防止无序写入。内存模型指定了重新排序的位置,部分是根据锁定。锁定确保在instance = inst;之后没有写入(包括单例构造函数中的任何内容)。

The point of locking twice was to attempt to prevent out-of-order writes. The memory model specifies where reorderings can occur, partly in terms of locks. The lock ensures that no writes (including any within the singleton constructor) appear to happen after the "instance = inst;" line.

但是,为了更深入地讨论这个问题,我建议 Bill Pugh的文章。然后永远不要尝试:)

However, to go deeper into the subject I'd recommend Bill Pugh's article. And then never attempt it :)

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

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