# Compare-And-Swap Pattern

> Compare-and-swap for lock-free updates: a runnable model of concurrent CAS retries on a shared value, checked so the value stays valid under every interleaving.

Canonical: https://fizzbee.io/design/patterns/compare-and-swap/
Source: https://github.com/fizzbee-io/fizzbee/tree/main/examples/references/13-03-03-compare-and-swap


Atomic compare-and-swap for lock-free algorithms

**Demonstrates:** CAS operation, lock-free updates, ABA problem awareness

```fizz
# Example 0077: Compare-And-Swap Pattern
# Atomic compare-and-swap for lock-free algorithms
# Demonstrates: CAS operation, lock-free updates, ABA problem awareness

action Init:
    shared_value = 0
    operations = 0

atomic action CASIncrement:
    require operations < 3

    # Read current value
    expected = shared_value
    new_value = expected + 1

    # CAS: update only if value unchanged
    if shared_value == expected:
        shared_value = new_value
        operations = operations + 1

atomic action CASDecrement:
    require operations < 3
    require shared_value != 0

    # Read current value
    expected = shared_value
    new_value = expected - 1

    # CAS: update only if value unchanged
    if shared_value == expected:
        shared_value = new_value
        operations = operations + 1

atomic action CASSet:
    require operations < 3

    # Direct set to specific value
    expected = shared_value
    target = 10

    if shared_value == expected:
        shared_value = target
        operations = operations + 1

# Safety: value changes atomically
always assertion ValidValue:
    return shared_value >= 0

# Safety: operations bounded
always assertion OperationsBounded:
    return operations <= 3

atomic action NoOp:
    if operations >= 3:
        pass
```
Run it in the FizzBee playground: https://fizzbee.io/play


**Expected result** (from `fizz`):

```
StateSpaceOptions: options:{max_actions:100 max_concurrent_actions:2}
Nodes: 15, queued: 0
Valid Nodes: 15 Unique states: 15
IsLive: true
PASSED: Model checker completed successfully
```

[Source on GitHub](https://github.com/fizzbee-io/fizzbee/tree/main/examples/references/13-03-03-compare-and-swap)

## Language features used

[Assertions](/reference/language/assertions/), [Flow Modifiers](/reference/language/flow-modifiers/)

