假设您有以下类(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
方法如何确定相等性 在prev
和newValue
之间?实现 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/