package Juc;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;
/**
* ABA问题:
* 银行服务器存在重复提交问题
* 银行一账户100元,A用户取走50元,(在B用户存款50元),重复提交的另外一线程挂起后唤醒发现数据未变化就也扣款50元.
* @date
*
*/
public class ABADemo
{ //ABA解决方案 AtomicStampedReference
static AtomicReference<Integer> at=new AtomicReference<>(100);
static AtomicStampedReference<Integer> atm = new AtomicStampedReference<Integer>(100, 1);
public static void main(String[] args)
{
System.out.println("================以下是ABA问题的产生========================");
new Thread(() -> {
at.compareAndSet(100, 101);
at.compareAndSet(101, 100);
},"t1").start();
new Thread(() -> {
//暂停一秒钟线程,保证上面的t1线程完成一次ABA操作
try {TimeUnit.SECONDS.sleep(1);} catch (Exception e) {e.printStackTrace();}
System.out.println(at.compareAndSet(100, 2019)+"\t "+at.get());
},"t2").start();
try {TimeUnit.SECONDS.sleep(2);} catch (Exception e) {e.printStackTrace();}
System.out.println("=============以下是ABA问题的解决===========");
new Thread(() -> {
int stamp=atm.getStamp();
System.out.println(Thread.currentThread().getName()+"\t 第1次版本号:"+ stamp);
//暂停1秒钟t3线程
try {TimeUnit.SECONDS.sleep(1);} catch (Exception e) {e.printStackTrace();};
atm.compareAndSet(100, 101, atm.getStamp(), atm.getStamp()+1);
System.out.println(Thread.currentThread().getName()+"\t 第2次版本号:"+ atm.getStamp());
atm.compareAndSet(101, 100, atm.getStamp(), atm.getStamp()+1);
System.out.println(Thread.currentThread().getName()+"\t 第3次版本号:"+ atm.getStamp());
},"t3").start();
new Thread(() -> {
int stamp=atm.getStamp();
System.out.println(Thread.currentThread().getName()+"\t 第一次版本号:"+ stamp);
//暂停3秒钟t4线程,保证上面的t3线程完成了一次ABA操作
try {TimeUnit.SECONDS.sleep(3);} catch (Exception e) {e.printStackTrace();};
boolean result=atm.compareAndSet(100, 2019, stamp, stamp+1);
System.out.println(Thread.currentThread().getName()+"\t 修改成功是否:"+result+" \t 当前最新实际版本号:"+atm.getStamp());
System.out.println(Thread.currentThread().getName()+"\t 当前实际最新值:"+atm.getReference());
},"t4").start();
}
}
CAS是乐观锁的一种实现,可以用版本号来预防ABA问题,
但CAS实现有诸多限制,单一变量原子性,自旋耗cpu性能。
优点:不加锁实现原子操作,在高并发,复杂业务多变量存在问题。