当前位置:网站首页>JUC atomic reference and ABA problem
JUC atomic reference and ABA problem
2022-06-13 09:05:00 【Q z1997】
JUC Atomic reference
- AtomicReference
- AtomicMarkableReference
- AtomicStampedReference
class DecimalAccountSafeCas implements DecimalAccount {
AtomicReference<BigDecimal> ref;
public DecimalAccountSafeCas(BigDecimal balance) {
ref = new AtomicReference<>(balance);
}
@Override
public BigDecimal getBalance() {
return ref.get();
}
@Override
public void withdraw(BigDecimal amount) {
while (true) {
BigDecimal prev = ref.get();
BigDecimal next = prev.subtract(amount);
if (ref.compareAndSet(prev, next)) {
break;
}
}
}
}
ABA Problems and Solutions
ABA problem
static AtomicReference<String> ref = new AtomicReference<>("A");
public static void main(String[] args) throws InterruptedException {
log.debug("main start...");
// Get value A
// This shared variable has been modified by its thread ?
String prev = ref.get();
other();
sleep(1);
// Try to change to C
log.debug("change A->C {}", ref.compareAndSet(prev, "C"));
}
private static void other() {
new Thread(() -> {
log.debug("change A->B {}", ref.compareAndSet(ref.get(), "B"));
}, "t1").start();
sleep(0.5);
new Thread(() -> {
log.debug("change B->A {}", ref.compareAndSet(ref.get(), "A"));
}, "t2").start();
}
The main thread can only judge the value of the shared variable from the initial value A Are they the same? , Can't perceive this from A Change it to B also Change back A The situation of , If the main thread wants :
As long as there are other threads 【 I've moved 】 Shared variables , So own cas Even if it fails , At this time , Just comparing values is not enough , You need to add another version number
AtomicStampedReference
static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A", 0);
public static void main(String[] args) throws InterruptedException {
log.debug("main start...");
// Get value A
String prev = ref.getReference();
// Get version number
int stamp = ref.getStamp();
log.debug(" edition {}", stamp);
// If there are other threads in the middle , It happened. ABA The phenomenon
other();
sleep(1);
// Try to change to C
log.debug("change A->C {}", ref.compareAndSet(prev, "C", stamp, stamp + 1));
}
private static void other() {
new Thread(() -> {
log.debug("change A->B {}", ref.compareAndSet(ref.getReference(), "B",
ref.getStamp(), ref.getStamp() + 1));
log.debug(" The updated version is {}", ref.getStamp());
}, "t1").start();
sleep(0.5);
new Thread(() -> {
log.debug("change B->A {}", ref.compareAndSet(ref.getReference(), "A",
ref.getStamp(), ref.getStamp() + 1));
log.debug(" The updated version is {}", ref.getStamp());
}, "t2").start();
}
AtomicStampedReference You can add version numbers to atomic references , Track the whole process of atomic reference , Such as : A -> B -> A -> C , adopt AtomicStampedReference, We can know , The reference variable was changed several times in the middle of the way . But sometimes , I don't care how many times the reference variable has changed , Just care about whether it has been changed , So there it is AtomicMarkableReference

AtomicMarkableReference
class GarbageBag {
String desc;
public GarbageBag(String desc) {
this.desc = desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return super.toString() + " " + desc;
}
}
@Slf4j
public class TestABAAtomicMarkableReference {
public static void main(String[] args) throws InterruptedException {
GarbageBag bag = new GarbageBag(" Full of garbage ");
// Parameters 2 mark It can be regarded as a mark , Indicates that the garbage bag is full
AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);
log.debug(" The main thread start...");
GarbageBag prev = ref.getReference();
log.debug(prev.toString());
new Thread(() -> {
log.debug(" Cleaning thread start...");
bag.setDesc(" Empty garbage bags ");
while (!ref.compareAndSet(bag, bag, true, false)) {
}
log.debug(bag.toString());
}).start();
Thread.sleep(1000);
log.debug(" The main thread wants to change a new garbage bag ?");
boolean success = ref.compareAndSet(prev, new GarbageBag(" Empty garbage bags "), true, false);
log.debug(" Did you change it ?" + success);
log.debug(ref.getReference().toString());
}
}
边栏推荐
- 20211108 A转置乘A是正定矩阵吗?A转置乘A是正定矩阵的充分必要条件是什么?
- 20211006 integral, differential and projection belong to linear transformation
- turf. JS usage
- 20211006 线性变换
- Cesium achieves sunny, rainy, foggy, snowy and other effects
- ES6 module import / export summary
- Module build failed: TypeError: this. getOptions is not a function at Object. stylusLoader
- 20211108 能观能控,可稳可测
- Tutorial (5.0) 01 Product introduction and installation * fortiedr * Fortinet network security expert NSE 5
- 共享模型之不可变
猜你喜欢

Neo4j - CQL使用
![[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp](/img/16/907c7c414502b22129f774fbffdafe.png)
[network security penetration] if you don't understand CSRF? This article gives you a thorough grasp

How many TCP connections can a machine create at most?

Tutorial (5.0) 01 Product introduction and installation * fortiedr * Fortinet network security expert NSE 5

How to become a white hat hacker? I suggest you start from these stages

How excel adds hyperlinks to some text in a cell

redis 模糊查询 批量删除

教程篇(5.0) 03. 安全策略 * FortiEDR * Fortinet 网络安全专家 NSE 5

20220606 关于矩阵的Young不等式

基于微信小程序的图书馆管理系统.rar(论文+源码)
随机推荐
[QNX hypervisor 2.2 user manual] 4.5 building a guest
【QNX Hypervisor 2.2 用户手册】4.5.1 构建QNX Guest
Judgment of single exclamation point and double exclamation point in JS
20211005 Hermite matrix and some properties
MySQL startup error: innodb: operating system error number 13 in a file operation
Diversified tables through TL table row consolidation
20211028 adjustment and tracking
Problèmes et traitement du disque gbase 8a
A very detailed blog about the implementation of bilinear interpolation by opencv
Tensorflow1.14 corresponds to numpy version
Top+jstack to analyze the causes of excessive CPU
Jfinal and swagger integration
Three indexes reflecting system reliability in performance test: MTTF, MTTR and MTBF
Collection of various books
pytorch统计模型的参数个数
The Jenkins console does not output custom shell execution logs
JS format file unit display
20211018 some special matrices
20211115 任意n阶方阵均与三角矩阵(上三角或者下三角)相似
Map 23 summary