java - AtomicReference.compareAndSet() 使用什么来确定?

标签 java concurrency atomic

假设您有以下类(class)

public class AccessStatistics {
  private final int noPages, noErrors;
  public AccessStatistics(int noPages, int noErrors) {
    this.noPages = noPages;
    this.noErrors = noErrors;
  }
  public int getNoPages() { return noPages; }
  public int getNoErrors() { return noErrors; }
}

然后执行以下代码

private AtomicReference<AccessStatistics> stats =
  new AtomicReference<AccessStatistics>(new AccessStatistics(0, 0));

public void incrementPageCount(boolean wasError) {
  AccessStatistics prev, newValue;
  do {
    prev = stats.get();
    int noPages = prev.getNoPages() + 1;
    int noErrors = prev.getNoErrors;
    if (wasError) {
      noErrors++;
    }
    newValue = new AccessStatistics(noPages, noErrors);
  } while (!stats.compareAndSet(prev, newValue));
}

最后一行中 while (!stats.compareAndSet(prev, newValue)) compareAndSet 方法如何确定相等性 prevnewValue之间?实现 equals() 方法是否需要 AccessStatistics 类?如果没有,为什么? javadoc 为 AtomicReference.compareAndSet

声明了以下内容

Atomically sets the value to the given updated value if the current value == the expected value.

...但是这个断言似乎非常笼统,而且我在 AtomicReference 上读过的教程从未建议为 AtomicReference 中包装的类实现 equals() 。

如果需要 AtomicReference 中包装的类来实现 equals(),那么对于比 AccessStatistics 更复杂的对象,我认为同步更新对象的方法而不使用 AtomicReference 可能会更快。

最佳答案

它会完全比较引用,就像您使用 == 运算符一样。这意味着引用必须指向同一个实例。未使用 Object.equals()。

关于java - AtomicReference.compareAndSet() 使用什么来确定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1869959/

相关文章:

multithreading - 给定足够的内存,当只有一个专用的写线程时,是否不需要锁?

java - 同步方法与 ReentrantLock

swift - Swift 中的并发和锁

java - 如何确保为该线程分配了一个唯一的 id

java - JTabbedPane 与 JTextAreas。自动向下滚动

Java 同步和在文本 Pane 中写入

Java boolean 表达式并发行为

java - Archunit 包 A 不能访问包 B,除了子包 A.X 可以访问 B.Y

java - 显示 Firebase 存储中的数据

java - Android Studio : W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED