是否可以安全地假设 (AtomicInteger a).addAndGet(-1)
之前的代码将始终在此调用之前执行,即 JVM 不会重新排序关于 addAndGet
调用的说明?
如果是,假设其他线程检查同一 AtomicInteger
实例的状态是否安全(例如 if (a.compareAndSet(0, -1))
) 会看到第一个线程在 addAndGet
调用之前更改的所有内容吗?
最佳答案
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
将发布一个 volatile 存储(或类似的),因此其他加载和存储无法在其下重新排序。
编辑:感谢 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.
关于java - 是否允许 JVM 围绕 AtomicInteger 调用重新排序指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32765053/