java - 评论 "Concurrency in Practice"

标签 java multithreading concurrency

@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/

相关文章:

java - 如何保证集合中项目的顺序

java - logcat 充满 java.io.IOException : Connection refused messages

Java - Thread join() 和执行顺序 SCJP 问题?

java - 如果我自己不中断任何事情,我是否需要担心 InterruptedExceptions?

c++ - 如何同步访问 NAS 上文件的两个进程?

java - 在变化数量的线程中并发重复相同的任务

java - 绕圈移动物体 - android

Java 单例和同步

java - 线程池的设计模式

Java 可变变量