I got some questions about AtomicReference.compareAndSet() method, according to the doc, it said:
Atomically sets the value to the given updated value if the current value == the expected value.
As far as I understand, the ==
operator is comparing the address of two objects, if so how will it work in examples like this
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 this code snippet, how does jvm know which fields of AccessStatistics
are to be compared in the compareAndSet()
? In fact I'm just wondering how is this whole strategy working given java doesn't allow to override ==
at all?
Thanks for any comments!