Evgeniy Berezovsky
Evgeniy Berezovsky

Reputation: 19218

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.

Upvotes: 5

Views: 1158

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

The API does not expose such a method. What's more, the Oracle implementation uses sun.misc.Unsafe to do the native CAS operation and that type doesn't expose it either.

One option is to just call get() if compareAndSet returned false. However, by the time you check it, the actual value of the AtomicInteger might have changed. There's not much you can do with it. This is true for Interlocked methods as well. You'd have to clarify what you want to do with that value to go any further.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198033

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.)

Upvotes: 2

Related Questions