【问题标题】:While loop in Singleton instead of if block单例中的while循环而不是if块
【发布时间】:2020-07-10 15:22:57
【问题描述】:

我在使用 DoubleLocking 创建单例时遇到了以下代码

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

使用while loop 而不是通常的if block 有什么意义?是不是因为某些JMM issues 可能会影响多线程环境中的单例创建?

【问题讨论】:

  • 那是不必要的。它只会循环一次,所以相当于if。
  • 关于双重检查锁定的问题是它很难正确处理(甚至 Josh Bloch 在 Effective Java 3rd 的第一次印刷中就弄错了Ed),所以人们会做……奇怪的事情,“以防万一”。

标签: java multithreading singleton


【解决方案1】:

使用while 循环是不必要的。

每个循环只会执行零次或一次,所以它们等价于 if。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 2012-02-14
    • 2020-12-10
    • 2022-09-29
    • 2014-01-14
    • 2015-01-04
    • 2020-08-14
    相关资源
    最近更新 更多