CAS的ABA问题
public class ABATest {
static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1,1);//(初始值,版本号)
public static void main(String[] args) {
new Thread(()->{
int stamp = atomicStampedReference.getStamp();//获取版本号
System.out.println("a1: "+stamp);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicStampedReference.compareAndSet(1, 2
, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));//cas改变初始值的大小
System.out.println("a2: "+atomicStampedReference.getStamp());//获取版本号
System.out.println(atomicStampedReference.compareAndSet(2, 1
, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));//cas改会初始值的大小
System.out.println("a3: "+atomicStampedReference.getStamp());//获取版本号
},"a").start();
new Thread(()->{
System.out.println("b1: "+atomicStampedReference.getStamp());//获取版本号
System.out.println( atomicStampedReference.compareAndSet(1, 66
, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));//cas改会初始值的大小
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b2: "+atomicStampedReference.getStamp());
},"b").start();
}
}
注意:
Integer 使用了对象缓存机制,默认范围是 -128 ~ 127 ,推荐使用静态工厂方法 valueOf 获取对象实
例,而不是 new,因为 valueOf 使用缓存,而 new 一定会创建新的对象分配新的内存空间;