5

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:

  1. The value stored in count is copied to a temporary variable.
  2. The temporary variable is incremented.
  3. 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.

  1. 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?

  1. 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

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
driftwood
  • 2,051
  • 4
  • 21
  • 28

1 Answers1

0

The values being compared are loaded into two+ registers (three in your example). Then it might use an instruction like CMPXCHG8B which is described (in part) as

Compare EDX:EAX with m64. If equal, set ZF and load ECX:EBX into m64. Else, clear ZF and load m64 into EDX:EAX.

The third value above might be in a different register, like ECX (or EBX) or some other location (just not EAX or EDX). You might refer to the Wikipedia entry on Compare and Swap for other implementations (that don't necessarily use assembler).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249