Difference between getAndSet and compareAndSet in AtomicBoolean

前端 未结 4 1265
攒了一身酷
攒了一身酷 2021-01-04 01:00

The thread title should be self-explnatory... I\'m a bit confused between the specification of below methos from AtomicBoolean class:

  • java.u
4条回答
  •  醉梦人生
    2021-01-04 01:41

    The thread is a bit old but nobody mentioned that getAndSet will be more efficient than compareAndSet. CAS is a very costly instruction (on all CPU architectures, so JVM does not matter here). So they are not really equivalent.

    So regarding the OP, both methods produce the same behaviour but it will not have the same performance, use getAndSet when you can.

提交回复
热议问题