单例双重检查锁定在高版本JDK(例如jdk11、14)中是否仍需要volatile?

huangapple go评论173阅读模式
英文:

Does singleton double-checked locking still need volatile in high version JDK (e.g. jdk11, 14)?

问题

在Java的单例模式中,大多数人告诉我们需要使用volatile关键字来防止指令重排序,但有人告诉我在高版本的JDK中不再需要volatile,他说得对吗?如果是这样,为什么呢?

public class SafeDCLFactory {
  private volatile Singleton instance;

  public Singleton get() {
    if (instance == null) {  // 检查1
      synchronized(this) {
        if (instance == null) { // 检查2
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}
英文:

In Java singleton, most people told us we need volatile to prevent instruction reordering, but someone told me it no longer needs volatile in high version JDK, is he right? If so, why?

public class SafeDCLFactory {
  private volatile Singleton instance;

  public Singleton get() {
    if (instance == null) {  // check 1
      synchronized(this) {
        if (instance == null) { // check 2
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}

答案1

得分: 5

在高版本的JDK(例如jdk11或jdk14)中,单例双重检查锁定是否仍然需要volatile?

是的,仍然需要。从Java 5开始的所有版本都要求instancevolatile的。

(在Java 5之前,无论instance是否被声明为volatile,上述代码都不可靠。)

... 有人告诉我现在不再需要volatile了...

我会对那个“某人”提出质疑,要求他们提供可靠的来源(或“happens-before”证明)来支持他们的说法。如果他们是正确的,他们构建证明所需的所有信息都在JLS 17.4中...适用于相关的Java版本。

英文:

> Does singleton double-checked locking still need volatile in high version JDK (e.g. jdk11 or jdk14)?

Yes it does. All versions of Java from Java 5 onwards require instance to be volatile.

(Prior to Java 5 the above code did not work reliably, whether instance was declared as volatile or not.)

> ... someone told me it no longer needs volatile ...

I would challenge that "someone" to provide a credible source (or a "happens-before" proof) to back up their assertion. If they are correct, all the information they need to construct a proof is in JLS 17.4 ... for the relevant Java version.

huangapple
  • 本文由 发表于 2020年5月5日 20:35:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/61613285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定