AtomicReference.compareAndSet()用于确定什么?

Rap*_*ier 5 java concurrency atomicity

假设您有以下课程

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; }
}
Run Code Online (Sandbox Code Playgroud)

然后执行以下代码

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));
}
Run Code Online (Sandbox Code Playgroud)

在最后一行while (!stats.compareAndSet(prev, newValue))中,该compareAndSet方法如何确定prev和之间的相等newValue?是AccessStatistics必需的类来实现的equals()方法?如果没有,为什么?Javadoc指出以下内容AtomicReference.compareAndSet

如果当前值==期望值,则以原子方式将该值设置为给定的更新值。

...但是这个断言似乎很笼统,我在AtomicReference上阅读的教程从不建议对包裹在AtomicReference中的类实施equals()。

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

Mik*_*els 5

就像您使用==运算符一样,它完全比较这些参考值。这意味着引用必须指向相同的实例。不使用Object.equals()。