What is the difference between AtomicBoolean.set(flag) and AtomicBoolean.compareAndSet(!flag, flag)?
compare-and-swap, java, java.util.concurrent
Solution
`compareAndset(false, true)` will return `false` if the value is already `true`. It's actually equivalent to `!getAndSet(true)`.
Problem
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?