SimulatedCAS.java
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