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