立即学习:https://edu.csdn.net/course/play/26270/326874?utm_source=blogtoedu
一、乐观锁和悲观锁的区别
二、CAS 乐观锁
- CAS 解释
全名:compare and swap,先比较后设置,CAS 是一个原子操作
- 适用场景
更新一个值,不依赖于加锁实现,可以接受CAS失败
- 局限
只可以更新一个值,如AtomicReference、AtomicInteger需要同时更新时,无法做到原子性。
从源码中分析:expect为原来的值,update为更新的值。如果程序要将 1 改为 2。则只有 expect =1时,才能成功把值update为2。
AtomicInteger 类中的 compareAndSwapInt 方法是 native 方法,是调用 JNI 的方法,底层其实就是通过一个CPU指令完成。
三、CAS 的自旋问题
如果CAS不成功,则会不停循环,原地自旋,长时间自旋自然会给CPU带来非常大的开销。
四、ABA 问题
线程1 : 将 value A->B
线程2 : 将 value A->C
但是在整个时间线上,虽然最终线程2能够将 A->C,但是线程2不知道中间 value 是变更过的。
五、AtomicStampedReference 如何处理 ABA 问题
public class AtomicStampedReference<V> {
private static class Pair<T> {
final T reference; // 当前属性的值
final int stamp; // 时间戳
private Pair(T reference, int stamp) {
this.reference = reference;
this.stamp = stamp;
}
static <T> Pair<T> of(T reference, int stamp) {
return new Pair<T>(reference, stamp);
}
}
...
/**
* Atomically sets the value of both the reference and stamp
* to the given update values if the
* current reference is {@code ==} to the expected reference
* and the current stamp is equal to the expected stamp.
*
* @param expectedReference the expected value of the reference
* @param newReference the new value for the reference
* @param expectedStamp the expected value of the stamp
* @param newStamp the new value for the stamp
* @return {@code true} if successful
*/
public boolean compareAndSet(V expectedReference,
V newReference,
int expectedStamp, // 期望的时间戳
int newStamp // 新的时间戳) {
Pair<V> current = pair;
return
expectedReference == current.reference && // 只有当期望的时间戳和当前value记录的时间戳一致,才允许更新
expectedStamp == current.stamp &&
((newReference == current.reference &&
newStamp == current.stamp) ||
casPair(current, Pair.of(newReference, newStamp)));
}
...
}
引入 timestamp ,记录对象当前时间戳。记录期望更改value时的时间戳,和当前 value 的时间戳进行对比,只有相等才能够进行更新。