Java compare and swap semantics and performance

后端 未结 3 596
再見小時候
再見小時候 2020-12-08 04:50

What is the semantics of compare and swap in Java? Namely, does the compare and swap method of an AtomicInteger just guarantee ordered access between different

3条回答
  •  没有蜡笔的小新
    2020-12-08 04:50

    weakCompareAndSwap is not guaranteed to be faster; it's just permitted to be faster. You can look at the open-source code of the OpenJDK to see what some smart people decided to do with this permission:

    • source code of compareAndSet

    • source code of weakCompareAndSet

    Namely: They're both implemented as the one-liner

    return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
    

    They have exactly the same performance, because they have exactly the same implementation! (in OpenJDK at least). Other people have remarked on the fact that you can't really do any better on x86 anyway, because the hardware already gives you a bunch of guarantees "for free". It's only on simpler architectures like ARM that you have to worry about it.

提交回复
热议问题