java - 是否允许 JVM 围绕 AtomicInteger 调用重新排序指令

标签 java multithreading concurrency jvm atomicinteger

是否可以安全地假设 (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/

相关文章:

java - 无法解析方法 openFileInput(Android 开发)

java - Activity 未停止响应

Java Swing : JPanels painting over each other

c++ - 接收输入时运行后台循环 (C++)

multithreading - TCriticalSection 有很多读者和一个作者

c++ - 使用 std::cin 语句使自动超时

python - Python mmap 和 multiprocessing.semaphore 的竞争条件

java - Spring,在一个查询中向现有的多对多列表添加一列

java - 为什么要在静态锁成员而不是类上进行同步?

java - Executor/Queue 仅处理最后一个已知任务