Atomic Markable Reference Swap
Track a value and a mark bit together with AtomicMarkableReference, testing compareAndSet and attemptMark transitions.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.MIME Type LookupResolve a file extension, file name, or MIME type to its media type, category, and related extensions using a local reference table.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.