编程语言
首页 > 编程语言> > java – AtomicReference.compareAndSet()用于确定什么?

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

作者:互联网

说你有以下课程

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方法如何确定prev和newValue之间的相等性?是否需要AccessStatistics类来实现equals()方法?如果没有,为什么? 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的方法可能会更快.

解决方法:

它比较使用==运算符完全比较refrerences.这意味着引用必须指向同一个实例.不使用Object.equals().

标签:java,concurrency,atomicity
来源: https://codeday.me/bug/20190607/1192000.html