`volatile Double` 的跨线程可见性

cross-thread visibility of `volatile Double`

volatile Double 是否像 volatile double 那样具有跨线程可见性?

来自 Java Tutorials at Oracle 的内容如下:

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads. What's more, it also means that when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.

这似乎取决于 Double 是一种特殊的对象还是没有任何特殊之处的对象。

是的,当任何线程随后访问该变量时,保证可以看到一个线程中对 volatile 变量的更改,无论该变量是原始类型还是引用类型。但是,这 不会 防止线程同步问题 - 您仍然必须确保两个线程不会同时尝试更改变量。

volatile Double bigD = new Double(1.0); 
bigD = 2.0;
正如 jtahlborn 所指出的,

Double 是一个不可变的 class。原始对象实例没有变化,因为它是不可变的。对 bigD 的更改必然是参考更改。该更改受益于 volatile 声明引起的跨线程可见性。

A list of Java immutables.

Examples of Java immutables.