如何避免在 Java 中使用 volatile

How to avoid using volatile in Java

我有两个线程共享相同的布尔类型变量。我发现我必须使用 volatile 来保证值总是从主内存中读取。但是现在我想摆脱这个易失性标识符,我该如何实现呢?我真的可以轻松地将我的布尔值 属性 提取到一个对象中吗?由于对对象的引用永远不会改变,线程将始终从主内存访问正确的值。这行得通吗?

如果您不喜欢该关键字,您也可以使用 AtomicBoolean 代替 - 这也将允许写入访问也是线程安全的

I have to use volatile to guarantee the value is always read from main memory

那不是 volatile 的工作方式。 volatile 用于建立 happens-before 关系:

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.

——来自doc.

But now I want to get rid of this volatile identifier, how can I achieve that?

如另一个答案中所说,您可以使用AtomicBoolean。或者,在 reading/writing 这个变量的代码周围添加 synchronized 块。或者使用其他一些 mechanism,它们可以在不同线程中读取和写入此变量之间建立 happens-before 关系。

Is it true that I easily can extract my boolean property into an object. As the reference to object never change the thread will always access the correct value from the main memory. Will this work?

没有。引用不会改变,这并不意味着新对象在更新后对其他读取线程总是可见的。