212
212

Reputation: 975

Is non-blocking CAS in Java really non-blocking?

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?

Upvotes: 2

Views: 505

Answers (1)

kryger
kryger

Reputation: 13181

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.

Upvotes: 3

Related Questions