compareAndSet和weakCompareAndSet区别

JDK1.9以前,两者底层实现是一样的,并没有严格区分。JDK 1.9提供了Variable Handles的API,主要是用来取代java.util.concurrent.atomic包以及sun.misc.Unsafe类的功能。Variable Handles需要依赖jvm的增强及编译器的协助,即需要依赖java语言规范及jvm规范的升级。

VarHandle中compareAndSet和compareAndSet的定义如下:

Modifier and Type Method Description
boolean compareAndSet(Object... args) Atomically sets the value of a variable to the newValue with the memory semantics of set(java.lang.Object...) if the variable's current value, referred to as the witness value== the expectedValue, as accessed with the memory semantics of getAcquire(java.lang.Object...).
boolean weakCompareAndSet(Object... args) Possibly atomically sets the value of a variable to the newValue with the memory semantics of setVolatile(java.lang.Object...) if the variable's current value, referred to as the witness value== the expectedValue, as accessed with the memory semantics of getVolatile(java.lang.Object...).

weakCompareAndSet的描述多了一个单词Possibly,可能的。weakCompareAndSet有可能不是原子的去更新值,这取决于虚拟机的实现。@HotSpotIntrinsicCandidate标注的方法,在HotSpot中都有一套高效的实现,该高效实现基于CPU指令,运行时,HotSpot维护的高效实现会替代JDK的源码实现,从而获得更高的效率。也就是说HotSpot可能会手动实现这个方法。

    @PolymorphicSignature
    @HotSpotIntrinsicCandidate
    public final native boolean compareAndSet(Object... var1);
    
    @PolymorphicSignature
    @HotSpotIntrinsicCandidate
    public final native boolean weakCompareAndSet(Object... var1);

 

你可能感兴趣的:(并发)