Difference between getAndSet and compareAndSet in AtomicBoolean

前端 未结 4 1287
攒了一身酷
攒了一身酷 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:20

    The documentation is pretty clear.

    • getAndSet --> "Atomically sets to the given value and returns the previous value."
    • compareAndSet --> "Atomically sets the value to the given updated value if the current value == the expected value."

    Not surprisingly, compareAndSet takes two arguments.

    In your specific case:

    • if (flag.getAndSet(false)) will set flag to false only if its previous value was true
    • That would be the equivalent of if (flag.compareAndSet(true, false))

提交回复
热议问题