有什么意义使用volatile long吗? [英] Is there any point in using a volatile long?

查看:244
本文介绍了有什么意义使用volatile long吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时会使用 volatile 实例变量,在这种情况下,我有两个线程从/写到它,并且不希望开销(或潜在的死锁风险)取出锁;例如定时器线程周期性地更新在某些类上作为getter暴露的int ID:

I occasionally use a volatile instance variable in cases where I have two threads reading from / writing to it and don't want the overhead (or potential deadlock risk) of taking out a lock; for example a timer thread periodically updating an int ID that is exposed as a getter on some class:

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;
  }
}

注意事项:请勿回复说使用 volatile over synchronized 是预优化的情况;我很清楚如何/何时使用同步,但有些情况下优先使用 volatile 。例如,当定义一个用于单线程应用程序的Spring bean时,我倾向于使用 volatile 实例变量,因为不能保证Spring上下文将初始化每个bean

My question: Given that the JLS only guarantees that 32-bit reads will be atomic is there any point in ever using a volatile long? (i.e. 64-bit).


推荐答案

不知道我是否正确理解你的问题,但 JLS 8.3.1.4。 volatile字段表示:

Not sure if I understand your question correctly, but the JLS 8.3.1.4. volatile Fields states:


字段可以声明为volatile,在这种情况下,Java内存模型确保所有线程都可以看到变量的一致值(§17.4 )。

,也许更重要的是, JLS 17.7双原子和长原子的非原子处理


17.7双原子和长子非原子对待

[...] $ $ b出于Java编程语言存储器模型的目的,对非易失性长或双值的单次写入被视为两个独立的写入:一个写入到每个32位的一半。这可能导致线程看到来自一次写入的64位值的前32位和来自另一次写入的第二32位的情况。 对volatile和double值的写入和读取总是原子的。对引用的写入和读取始终是原子的,无论它们是实现为32位还是64位值。

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修饰符保护,而不仅仅是两个部分。这诱使我声称对 long 使用volatile比 int 更重要 c $ c> s因为不是读取对于非易失性长整型/双精度是原子的。

That is, the "entire" variable is protected by the volatile modifier, not just the two parts. This tempts me to claim that it's even more important to use volatile for longs than it is for ints since not even a read is atomic for non-volatile longs/doubles.

这篇关于有什么意义使用volatile long吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆