Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Java's AtomicInteger offers public final boolean compareAndSet(int expect, int update). If false is returned, I would like to know what the value actually was at the time when the comparison failed. Is this possible in Java?

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

like image 804
Evgeniy Berezovsky Avatar asked Oct 31 '22 15:10

Evgeniy Berezovsky


1 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 sort of loop is how most operations on AtomicInteger are implemented: loops of get, do some logic, try compare-and-set.)

like image 126
Louis Wasserman Avatar answered Nov 11 '22 15:11

Louis Wasserman