I wonder if there is any difference(or possible side effects) between calling:
AtomicBoolean.set(true)
and
AtomicBoolean.compareAndset(false, true)
The JavaDoc of AtomicBoolean#set states:
Unconditionally sets to the given value.
While AtomicBoolean#compareAndSet states:
Atomically sets the value to the given updated value if the current value == the expected value.
In both cases the value will be set to true. So what is the difference?
compareAndset(false, true)will returnfalseif the value is alreadytrue.It’s actually equivalent to
!getAndSet(true).