AtomicInteger.compareAndSet, which returns the original value, not a boolean

Java AtomicIntegeroffers public final boolean compareAndSet(int expect, int update). If it returns false, I would like to know what value actually was at a time when the comparison failed. Is this possible in Java?

In .Net, public static int CompareExchange(ref int location1, int value, int comparand)which always returns the original value.

+4
source share
2 answers
public int getAndCompareAndSet(AtomicInteger ai, int expected, int update) {
  while (true) {
    int old = ai.get();
    if (old != expected) {
      return old;
    } else if (ai.compareAndSet(old, update)) {
      return old;
    }
  }
}

(This type of loop is how most of the operations on it are implemented AtomicInteger: get loops, do some logic, try to compare and install.)

+1
source

API . , Oracle sun.misc.Unsafe CAS-, .

- get(), compareAndSet false. , , AtomicInteger . . Interlocked. , , .

0

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


All Articles