Atomic variable in java - Compare and Swap

private AtomicInteger counter = new AtomicInteger();

public int getNextUniqueIndex() {
  return counter.getAndIncrement();
}
The AtomicInteger class uses CAS (compare-and-swap) low-level CPU operations (no synchronization needed!) They allow you to modify particular variable only if the present value is equal to something else (and return it it succeed). So when you execute getAndIncrement() it actually runs in a loop (simplified real implementation):
int current;
do {
  current = get();
} while(!compareAndSet(current, current + 1)
So basically: read, try to store incremeneted value, if not succeeded (the value is no longer equal to current) read and try again. The tryChanging() is implemented in native code (assembly)

0 comments: