Say you have the following 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; }
}
and you execute the following code
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));
}
In the last line, while (!stats.compareAndSet(prev, newValue))how does the method compareAndSet determine the equality between prevand newValue? Is a class required AccessStatisticsto implement the method equals()? If not, why? Javadoc states the following forAtomicReference.compareAndSet
Atomically sets the value for this updated value if the current value == expected value.
... but this statement seems very general, and the tutorials that I read on AtomicReference never assume the implementation of equals () for a class wrapped in AtomicReference.
, AtomicReference, equals(), , , AccessStatistics , , , AtomicReference.