What uses AtomicReference.compareAndSet () to determine?

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.

+3
3

, ==. , . Object.equals() .

+4

, prev newValue!

, , prev, , , , , newValue. , (==). , , prev , , .

+2

It just checks if the link to the object is equal (aka ==), so if the link to the object contained in AtomicReference has changed after you got the link, it will not change the link, so you have to start.

0
source

Source: https://habr.com/ru/post/1725092/


All Articles