Java 并发编程之 AtomicMarkableReference

Java juc About 1,486 words

说明

AtomicStampedReference解决了ABA问题,但需要每次修改版本号比较繁琐,AtomicMarkableReference只关心是否有改动。

代码

public class AtomicMarkableReferenceDemo {

    public static void main(String[] args) {
        AtomicMarkableReference<String> ref = new AtomicMarkableReference<>("A", false);
        boolean marked = ref.isMarked();
        String reference = ref.getReference();
        boolean b = ref.compareAndSet(reference, "B", marked, true);
        boolean b1 = ref.attemptMark("B", true);
        System.out.println(b1);
    }

}

源码解析

AtomicMarkableReference底层是使用Pair对象封装了referencemark字段。

compareAndSet底层源码是判断了Pair对象。

private volatile Pair<V> pair;

private static class Pair<T> {
    final T reference;
    final boolean mark;
    private Pair(T reference, boolean mark) {
        this.reference = reference;
        this.mark = mark;
    }
    static <T> Pair<T> of(T reference, boolean mark) {
        return new Pair<T>(reference, mark);
    }
}

public boolean compareAndSet(V       expectedReference,
                             V       newReference,
                             boolean expectedMark,
                             boolean newMark) {
    Pair<V> current = pair;
    return
        expectedReference == current.reference &&
        expectedMark == current.mark &&
        ((newReference == current.reference &&
          newMark == current.mark) ||
         casPair(current, Pair.of(newReference, newMark)));
}
Views: 1,724 · Posted: 2021-09-23

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh