I am studying the concurrent packages in a Java book. I don't quite understand something the book says about CAS operations. The following code sample is a thread-safe counter
class from the book.
public class Counter{
private AtomicInteger count = new AtomicInteger();
public void increment(){
count.getAndIncrement(); //atomic operation
}
....
}
Here is what the book says about it.
In reality, even a method such as
getAndIncrement()
still takes several steps to execute. The reason this implementation is now thread-safe is something called CAS. CAS stands for Compare And Swap. Most modern CPUs have a set of CAS instructions. A basic outline of what is happening now is as follows:
- The value stored in count is copied to a temporary variable.
- The temporary variable is incremented.
- Compare the value currently in count with the original value. If it is unchanged, then swap the old value for the new value.
OK I get what its saying about multiple steps. What I don't quite get are what's happening in the enumerated steps.
- The value stored in count is copied to a temporary variable.
Where is that temp variable? Is it in main memory, register? Or is this specific to the CPU architecture?
- Compare the value currently in count with the original value. If it is unchanged, then swap the old value for the new value.
Where is the original value stored? It can't be the temp variable. That one's being modified, right? What am I missing?
Thanks