@ThreadSafe
public class SynchronizedInteger {
@GuardedBy("this") private int value;
public synchronized int get() { return value; }
public synchronized void set(int value) { this.value = value; }
}
书上说:
A good way to think about volatile variables is to imagine that they behave roughly like the SynchronizedInteger class in Listing 3.3, replacing reads and writes of the volatile variable with calls to get and set.
...
This analogy is not exact; the memory visibility effects of SynchronizedInteger are actually slightly stronger than those of volatile variables. See Chapter 16.
我检查了第 16 章,但没有找到确切的答案 - 内存可见性保证到底有多强?
最佳答案
主要区别在于 volatile
在对 volatile
变量的写入和从中读取的子序列之间创建了先行关系,而 synchronized
在解锁和后续锁定之间创建先行关系。
因此,在 SynchronizedInteger
的情况下,会在使用 SychrozniedInteger
的任何后续操作之间创建先行关系(即 get()
和 set()
calls),不管是读还是写。它与 volatile int
的行为不同,volatile int
仅在写入和后续读取之间提供 happens-before。
实际上我想不出任何有意义的例子来说明这种差异,所以这些行为真的只是略有不同。
关于java - 评论 "Concurrency in Practice",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7257369/