js css html

java 原子类的CompareAndSet方法

2023-04-02  本文已影响0人  flyjar

CompareAndSet :通俗来说,就是比较ok,就set,否则就不set。

它是比synchronouse同步锁效率更高的一种cas乐观锁。

它是原子类AtomicBoolean下的方法。

所谓比较ok,就更新,否则不更新:这里就有两个比较值A和B,更新值C。

例如:A:是存线程中的一个值。B是比较值,C是更新值。

粗略用下图理解:如果线程1和线程2同时调用CompareAndSet方法,更新变量C的值,那现在线程1本地存临时值为10与内存的值10,比较是否相等,符合更新标准,则将内存中的变量C更新为11,返回true。

那线程2使用线程存储的临时变量12去与内存变量C的值10比较,不符合更新标准,则更新失败,返回fasle。


534e7389f9d64213963876eaf4dc0e25.png

compareAndSet 源码注释:

/**
 * Atomically sets the value to the given updated value
 * if the current value {@code ==} the expected value.
 *
 * @param expect the expected value
 * @param update the new value
 * @return {@code true} if successful. False return indicates that
 * the actual value was not equal to the expected value.
 */
public final boolean compareAndSet(boolean expect, boolean update) {
    int e = expect ? 1 : 0;
    int u = update ? 1 : 0;
    return unsafe.compareAndSwapInt(this, valueOffset, e, u);
}

我理解:this和valueOffset可以获取内存变量C的实际值,调用线程修改时expect和变量C一致,则说明当前没有线程修改过变量C,则符合更新条件,将update赋值到变量C。

上一篇 下一篇

猜你喜欢

热点阅读