1. ABA问题:在一个线程a将数值改成了b,又改成了a后,CAS认为该值没有变化,但实际上已经发生了变化。解决这个问题的方法是使用版本号标识,即每次更新时版本号加一。在Java5中,AtomicStampedReference被引入来解决这个问题。
import java.util.concurrent.atomic.AtomicStampedReference;
public class ABASolution {
private static AtomicStampedReference<Integer> atomicStampedRef =
new AtomicStampedReference<>(1, 0);
public static void main(String[] args) {
new Thread(() -> {
int stamp = atomicStampedRef.getStamp();
int value = atomicStampedRef.getReference();
System.out.println("线程1读取到的值:" + value);
System.out.println("线程1读取到的版本号:" + stamp);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean isCASSuccess = atomicStampedRef.compareAndSet(value, 2, stamp, stamp + 1);
System.out.println("线程1 CAS操作是否成功:" + isCASSuccess);
}).start();
new Thread(() -> {
int stamp = atomicStampedRef.getStamp();
int value = atomicStampedRef.getReference();
System.out.println("线程2读取到的值:" + value);
System.out.println("线程2读取到的版本号:" + stamp);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean isCASSuccess = atomicStampedRef.compareAndSet(value, 2, stamp, stamp + 1);
System.out.println("线程2 CAS操作是否成功:" + isCASSuccess);
}).start();
}
}
2.不能保证代码块的原子性:CAS机制只能保证一个变量的原子性操作,而不能保证整个代码块的原子性。例如,如果需要保证三个变量共同进行原子性的更新,就不得不使用其他同步机制,如synchronized
import java.util.concurrent.atomic.AtomicInteger;
public class NonAtomicBlock {
private static AtomicInteger atomicInt = new AtomicInteger(0);
private static int nonAtomicInt = 0;
public static void main(String[] args) {
new Thread(() -> {
int oldValue = atomicInt.get();
int newValue = oldValue + 1;
boolean isCASSuccess = atomicInt.compareAndSet(oldValue, newValue);
if (isCASSuccess) {
} else {
}
}).start();
new Thread(() -> {
int oldValue = nonAtomicInt;
int newValue = oldValue + 1;
nonAtomicInt = newValue;
}).start();
}
}
3.CPU利用率增加:由于CAS内部包含一个循环判断的过程,如果线程一直未能获取到状态,CPU资源会被持续占用,导致CPU利用率增加。