AtomicStampedReference:解决CAS的ABA问题
AtomicInteger无法知道中间值有没有被修改过,AtomicStampedReference通过整形final int stamp;来标记Integer值修改过多少次
代码示例:
public class MyAtomicStampedReference {
//版本是,以后每修改一次都会增加1,如果修改时和自己预料的版本不一致就会修改失败
static AtomicStampedReference<String> atomicStampedReference = new AtomicStampedReference("tom",10);
public static void main(String[] args) {
int oldStamp = atomicStampedReference.getStamp();
String oldReference = atomicStampedReference.getReference();
System.out.println("初始化之后的版本:"+oldStamp);
System.out.println("初始化之后的值:"+oldReference);
String newReference = "jerry";
boolean b =atomicStampedReference.compareAndSet(oldReference,newReference,1,oldStamp+1);
if(!b){
System.out.println("版本戳不一致,无法修改Reference的值");
}
b =atomicStampedReference.compareAndSet(oldReference,newReference,oldStamp,oldStamp+1);
if(b){
System.out.println("版本戳一致,修改reference的值为jerry");
}
System.out.println("修改成功之后的版本:"+atomicStampedReference.getStamp());
System.out.println("修改成功之后的值:"+atomicStampedReference.getReference());
}
}
运行结果:
初始化之后的版本:10
初始化之后的值:tom
版本戳不一致,无法修改Reference的值
版本戳一致,修改reference的值为jerry
修改成功之后的版本:11
修改成功之后的值:jerry