CAS 算法保证数据的原子性
CAS算法是硬件对于并发操作共享数据的支持
CAS包含三个操作数:
内存值 V
预估值A(比较前再次获取内存值)
更新值 B
首先,先去主存获取内存值 V,然后在比较前再次去主存获取内存值作为预估值 A,然后去比较V==A,如果为 true,则V=B;否则不做任何操作。
public class TestCAS {
public static void main(String[] args) {
final CompareAndSwap cas = new CompareAndSwap();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
int expect = cas.getValue();
boolean b = cas.compareAndSet(expect, (int) (Math.random() * 100));
System.out.println(b);
}
}).start();
}
}
}
class CompareAndSwap {
private int value;
/**
* 获取内存地址的值
*
* @return
*/
public synchronized int getValue() {
return value;
}
/**
* 如果内存地址的值等于expect,则将内存地址的值改为newValue
*
* @param expect 预估值
* @param newValue
* @return
*/
public synchronized int compareAndSwap(int expect, int newValue) {
int oldValue = value;
if (oldValue == expect) {
value = newValue;
}
return oldValue;
}
/**
* @param expect
* @param newValue
* @return
*/
public synchronized boolean compareAndSet(int expect, int newValue) {
return expect == compareAndSwap(expect, newValue);
}
}