java - 使用 volatile long 有什么意义吗?

标签 java multithreading concurrency volatile

我偶尔会使用 volatile 实例变量,因为我有两个线程读取/写入它并且不希望获取锁的开销(或潜在的死锁风险);例如,一个计时器线程定期更新一个 int ID,该 ID 作为某个类的 getter 公开:

public class MyClass {
  private volatile int id;

  public MyClass() {
    ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
    execService.scheduleAtFixedRate(new Runnable() {
      public void run() {
        ++id;
      }
    }, 0L, 30L, TimeUnit.SECONDS);
  }

  public int getId() {
    return id;
  }
}

我的问题:鉴于 JLS 仅保证 32 位读取将是原子的,曾经使用 volatile long 有什么意义吗? (即 64 位)。

警告:请不要回复说使用 volatile 而不是 synchronized 是预优化的情况;我很清楚如何/何时使用 synchronized 但在某些情况下 volatile 更可取。例如,在定义用于单线程应用程序的 Spring bean 时,我倾向于使用 volatile 实例变量,因为不能保证 Spring 上下文会在主线程中初始化每个 bean 的属性。

最佳答案

不确定我是否正确理解了您的问题,但 JLS 8.3.1.4. volatile Fields状态:

A field may be declared volatile, in which case the Java memory model ensures that all threads see a consistent value for the variable (§17.4).

也许更重要的是,JLS 17.7 Non-atomic Treatment of double and long :

17.7 Non-atomic Treatment of double and long
[...]
For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64 bit value from one write, and the second 32 bits from another write. Writes and reads of volatile long and double values are always atomic. Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.

也就是说,“整个”变量受到 volatile 修饰符的保护,而不仅仅是两个部分。这诱使我声称对 longs 使用 volatile 比对 ints 使用 volatile 甚至更重要,因为 甚至不是read 对于非 volatile longs/doubles 是原子的。

关于java - 使用 volatile long 有什么意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038203/

相关文章:

java - 从另一个 java 进程调用 java 使其停止

multithreading - 如何在线程之间共享非发送对象?

java - 显示一定数量的素数

java - 如何过滤 JAX-RS 中具有无效参数的请求?

ios - NSURLConnection发生无法解释的崩溃

c++ - 带线程的运算符++(前缀)

c++ - 使用 vector 作为多线程队列是否安全?

java - HTTP 代理连接共享

java - undefined variable 上的 BaseX XQJ API 错误,而变量已定义

multithreading - Await.result还是一个简单的电话?