Site Search:

SimulatedCAS.java

 SimulatedCAS.java

/**
* SimulatedCAS
* <p/>
* Simulated CAS operation
*
* @author Brian Goetz and Tim Peierls
*/

public class SimulatedCAS {
private int value;

public synchronized int get() {
return value;
}

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

public synchronized boolean compareAndSet(int expectedValue,
int newValue) {
return (expectedValue
== compareAndSwap(expectedValue, newValue));
}
}

The SimulatedCAS class demonstrates a conceptual implementation of a Compare-And-Swap (CAS) operation using Java's synchronized keyword to ensure atomicity. The method compareAndSwap(int expectedValue, int newValue) checks whether the current value matches the expected value and, if so, updates it to the new value. It returns the original value regardless of whether the update was successful. The compareAndSet method builds on this, returning a boolean to indicate success. While this version is not lock-free due to its reliance on synchronized, it illustrates the core idea behind CAS — which is the foundation for Java’s real atomic classes like AtomicInteger. This example is useful for understanding the mechanics of atomic updates before introducing hardware-supported, non-blocking CAS operations.

No comments:

Post a Comment