Question

I was going over an article on non-blocking CAS and came across this code:

public class SimulatedCAS {
  private int value;

  public synchronized int getValue() {
    return value;
  }

  public synchronized int compareAndSwap(int expectedValue, int newValue) {
     int oldValue = value;
     if (value == expectedValue)
         value = newValue;
     return oldValue;
  }
}

How is this CAS operation non-blocking if it uses synchronization?

If we mean the client of this SimulatedCAS need not implement synchronization of its own, then haven't we just moved the blocking around instead of eliminating it?

Was it helpful?

Solution

Note that this is a simulated CAS (as the name itself implies); in words of Brian Goetz (the listing comes from his "Java Concurrency In Practice" book):

SimulatedCAS in Listing 15.1 illustrates the semantics (but not the implementation or performance) of CAS.

Actual implementation of CAS needs CPU support, classes from the java.util.concurrent.atomic package call native methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top