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 TypeMethodDescription
booleancompareAndSet(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...).
booleanweakCompareAndSet(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);

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值