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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With