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
对象封装了reference
和mark
字段。
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,717 · Posted: 2021-09-23
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...