微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java双重检查锁定代码说明

如何解决Java双重检查锁定代码说明

我有一个我不明白的代码片段,我将突出显示让我困惑的地方。

private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;    // <---------- This bit,why do we assign it here ? 
    if (r == null) {
        synchronized (lock) {    // What is the benefit of this lock in here
            r = instance;        // assuming instance is null which will pass the first if ( r == null,what do we assign it again ?? I don't get the idea of this step at all. 
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}

我见过https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples,但其中的实现看起来像这样,没有两个分配。

public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    if(instance == null){
        synchronized (ThreadSafeSingleton.class) {
            if(instance == null){
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}

解决方法

from IPython.display import HTML
html = anim.to_html5_video()
HTML(html)

在这里真正想要的是关于局部变量的推理更容易。另外,读取 YourObject r = instance; // <---------- This bit,why do we assign it here ? 可能不被优化程序合并的变量的开销。

volatile

此锁可以防止多个线程同时创建和分配 synchronized (lock) { // What is the benefit of this lock in here 的不同实例。

YourObject

r = instance; // assuming instance is null which will pass the first if ( r == null,what do we assign it again ?? I don't get the idea of this step at all. 可能在instance校验的第一次读取与成功获取锁定之间已更改。

无论如何,不​​要使用双重检查锁定-这非常令人困惑,并且可能还有更好的方法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。