← 中文资源

简体中文版本

Atomic Markable Reference 交换

用 AtomicMarkableReference 同时维护值与标记位,测试 compareAndSet 与 attemptMark 的状态转换。

阅读英文原文

实现说明

Atomic Markable Reference 交换以类 Main和函数 main为骨架。

使用要点

  • 跑完文件,输出里会留下标记——value:、first cas:、now:。

常见问题

运行「Atomic Markable Reference 交换」会打印什么?

运行文件本身,value:、first cas:、now: 这些前缀各对应一段演示逻辑。

核心语句

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

代码示例

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]);
    }
}