Skip to content

AtomicMarkableReference 可以解决ABA问题 #1627

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 26, 2022
Merged

AtomicMarkableReference 可以解决ABA问题 #1627

merged 1 commit into from
Mar 26, 2022

Conversation

BaoPiao
Copy link
Contributor

@BaoPiao BaoPiao commented Mar 19, 2022

因为AtomicMarkableReference是通过内部类Pair实现数据存储,每次替换都是通过Pair.of方法new一个类出来进行替换原先的值
如果ABA出现,那么最后的A肯定是一个新的Pair实例,即当前的A和之前的A不是同一个实例,当线程使用compareAndSet则会返回false
以下是compareAndSet的实现:
public boolean compareAndSet(V expectedReference,
V newReference,
boolean expectedMark,
boolean newMark) {
Pair current = pair;
return
expectedReference == current.reference &&
expectedMark == current.mark &&
((newReference == current.reference &&
newMark == current.mark) ||
casPair(current, Pair.of(newReference, newMark)));
}

因为AtomicMarkableReference是通过内部类Pair实现数据存储,每次替换都是通过Pair.of方法new一个类出来进行替换原先的值
如果ABA出现,那么最后的A肯定是一个新的Pair实例,即当前的A和之前的A不是同一个实例,当现场使用compareAndSet则会返回false
以下是compareAndSet的实现:
Pair<V> current = pair;
        return
            expectedReference == current.reference &&
            expectedMark == current.mark &&
            ((newReference == current.reference &&
              newMark == current.mark) ||
             casPair(current, Pair.of(newReference, newMark)));
@Snailclimb Snailclimb merged commit 7d34a6c into Snailclimb:main Mar 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants