This is a classical example of CAS loop. The compare-and-set is an atomic operation which has direct hardware support (usually there's some CPU instruction behind it). It atomically updates the given variable only if current value is equal to the expected one and returns true if everything was successful. Normally this loop is executed only once. However under contention (when other threads try to update the same value) it's possible that between reading current value via get()
and updating it via compareAndSet
another thread managed to update it. In this case the whole procedure is retried until success.
Using infinite loop here is just a matter of style. It could be rewritten using normal do-while
loop:
public final int addAndGet(int delta) { int current, next; do { current = get(); next = current + delta; } while (!compareAndSet(current, next)); return next;}