解决cas的ABA问题时,compareAndSet执行一直为false
每次执行都是false,期望值获取都没问题,但是就是false
后来才发现是因为泛型为Integer的问题,
Integer对象值得范围在-128 ~127之间时公用同一块内存空间,所以超过该范围的数如果用‘’去比较即使值一样也是flase,相当于是new了一个Integer,不是一个加载器。
*cas用的应该时来进行比较的,所以才为flase,真是个大坑,找了半天源码 都没问题。*
public static void main(String[] args) {
AtomicStampedReference<Integer> atomicS=new AtomicStampedReference<>(1000,1);
new Thread(()->{
int stamp=atomicS.getStamp();
int init=atomicS.getReference();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("init-stamp"+stamp+" "+init);
System.out.println(atomicS.compareAndSet(1111, 1002,atomicS.getStamp(), atomicS.getStamp()+1));
System.out.println("first"+atomicS.getStamp());
System.out.println(atomicS.compareAndSet(1002, 1000, atomicS.getStamp(), atomicS.getStamp()+1));
System.out.println("second"+atomicS.getStamp());
}).start();
```
阿里开发手册上面页强调了这个坑
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200629194858736.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI2MDQ4Mjkz,size_16,color_FFFFFF,t_70)