Atomic Markable Reference Swap

Track a value and a mark bit together with AtomicMarkableReference, testing compareAndSet and attemptMark transitions.

JavaData Integrity

Code

snippet
import java.util.concurrent.atomic.AtomicMarkableReference;

public class Main {
    public static void main(String[] args) {
        AtomicMarkableReference<String> slot =
                new AtomicMarkableReference<>("draft", false);

        boolean[] mark = new boolean[1];
        System.out.println("value: " + slot.get(mark) + " marked: " + mark[0]);

        // compareAndSet matches both the reference and the mark bit
        boolean first = slot.compareAndSet("draft", "review", false, true);
        System.out.println("first cas: " + first);
        System.out.println("now: " + slot.getReference() + " marked: " + slot.isMarked());

        // a stale mark makes the same reference swap fail
        boolean second = slot.compareAndSet("review", "published", false, true);
        System.out.println("stale mark cas: " + second);

        // attemptMark changes only the mark when the reference still matches
        boolean attempted = slot.attemptMark("review", false);
        System.out.println("attemptMark: " + attempted + " marked: " + slot.isMarked());

        // get with a holder returns both fields from a single read
        boolean[] observed = new boolean[1];
        String value = slot.get(observed);
        System.out.println("observed: " + value + " " + observed[0]);
    }
}

How it works

One way to read it: the class Main and the function main, doing all the work.

Watch out for

  • Every symbol it touches is a language built-in — nothing to fetch.

Using it

Signature: public static void main(String[] args)

The run emits 3 labeled sections — value:, first cas:, now: — one per step.

Key statements

boolean second = slot.compareAndSet("review", "published", false, true);
boolean first = slot.compareAndSet("draft", "review", false, true);
boolean attempted = slot.attemptMark("review", false);

Interactive Tools for This Topic

FAQ

What does Atomic Markable Reference Swap print when run?
No setup needed: run the file and look for labeled lines like `value:`, `first cas:`, `now:` in the output.