假设您有以下课程
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))
如何确定和之间的相等性?类是实现方法所必需的吗?如果不是,为什么?javadoc 声明如下compareAndSet
prev
newValue
AccessStatistics
equals()
AtomicReference.compareAndSet
如果当前值 == 预期值,则自动将值设置为给定的更新值。
...但是这个断言似乎很笼统,我在 AtomicReference 上阅读的教程从未建议为包装在 AtomicReference 中的类实现 equals()。
如果需要封装在 AtomicReference 中的类来实现 equals(),那么对于比AccessStatistics
我想象的更复杂的对象,同步更新对象而不使用 AtomicReference 的方法可能会更快。