I have been reading JCIP by Brian Goetz. He explains the implementation of a non-blocking counter using CAS instruction. I could not understand how the increment is happening using CAS instruction. Can anyone help me understand this.
public class CasCounter {
private SimulatedCAS value;
public int getValue() {
return value.get();
}
public int increment() {
int v;
do {
v = value.get();
}
while (v != value.compareAndSwap(v, v + 1));
return v + 1;
}
}
value.compareAndSwap(v, v + 1)is equivalent to the following, except that the entire block is atomic: (see compare-and-swap for details)Now
v = value.get()gets the current value of the counter, and if nobody else is trying to update the counter at the same time,old == vwill be true, so the value is set tov+1(i.e. it is incremented) andoldis returned. The loop terminates sincev == old.Suppose someone else incremented the counter just after we did
v = value.get(), thenold == vwould be false, and the method will immediately returnold, which is the updated value. Sincev != oldnow, the loop continues.