是否允许 JVM 围绕 AtomicInteger 调用重新排序指令
Is JVM allowed to reorder instructions around AtomicInteger calls
假设 (AtomicInteger a).addAndGet(-1)
之前的代码将始终在此调用之前执行是否安全,即 JVM 不会 重新排列 [=11= 周围的指令]打电话?
如果是,是否可以安全地假设其他线程检查同一 AtomicInteger
实例的状态(例如 if (a.compareAndSet(0, -1))
)将看到第一个线程在 [=11= 之前更改的所有内容]打电话?
Is it safe to assume that the code before (AtomicInteger
a).addAndGet(-1) will be always executed before this call, i.e. JVM
will not reorder the instructions around the addAndGet call?
是的,没错。 addAndGet
将发布一个易失性存储(或类似的),因此其他加载和存储不能在它下面重新排序。
编辑:感谢 Soitrios 的链接 https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html,这表明已经为您建立了订单。
- get has the memory effects of reading a volatile variable.
- set has the memory effects of writing (assigning) a volatile variable.
- compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.
假设 (AtomicInteger a).addAndGet(-1)
之前的代码将始终在此调用之前执行是否安全,即 JVM 不会 重新排列 [=11= 周围的指令]打电话?
如果是,是否可以安全地假设其他线程检查同一 AtomicInteger
实例的状态(例如 if (a.compareAndSet(0, -1))
)将看到第一个线程在 [=11= 之前更改的所有内容]打电话?
Is it safe to assume that the code before (AtomicInteger a).addAndGet(-1) will be always executed before this call, i.e. JVM will not reorder the instructions around the addAndGet call?
是的,没错。 addAndGet
将发布一个易失性存储(或类似的),因此其他加载和存储不能在它下面重新排序。
编辑:感谢 Soitrios 的链接 https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html,这表明已经为您建立了订单。
- get has the memory effects of reading a volatile variable.
- set has the memory effects of writing (assigning) a volatile variable.
- compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.