首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java双重检查锁定代码解释

Java双重检查锁定代码解释
EN

Stack Overflow用户
提问于 2020-10-28 05:14:22
回答 1查看 38关注 0票数 0

我有一个我不理解的代码片段,我将强调一下让我困惑的部分。

代码语言:javascript
复制
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,但它的实现看起来像这样,它没有两个赋值。

代码语言:javascript
复制
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    if(instance == null){
        synchronized (ThreadSafeSingleton.class) {
            if(instance == null){
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-28 05:27:35

代码语言:javascript
复制
    YourObject r = instance;    // <---------- This bit, why do we assign it here ?

更容易推断局部变量,这是您在这里真正想要的。此外,在读取可能未被优化器合并的volatile变量时也会产生开销。

代码语言:javascript
复制
    synchronized (lock) {    // What is the benefit of this lock in here

这个锁可以防止多个线程同时创建和分配不同的YourObject实例。

代码语言:javascript
复制
        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. 

在第一次读取null检查和成功获取锁之间,instance可能已更改。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64562998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档