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?
AtomicBoolean has methods that perform their compound operations atomically and without having to use a synchronized block. On the other hand, volatile boolean can only perform compound operations if done so within a synchronized block.
compareAndSet() is an inbuilt method in java that sets the value to the passed value in the parameter if the current value is equal to the expected value which is also passed in the parameter. The function returns a boolean value which gives us an idea if the update was done or not.
AtomicBoolean class provides operations on underlying boolean value that can be read and written atomically, and also contains advanced atomic operations. AtomicBoolean supports atomic operations on underlying boolean variable. It have get and set methods that work like reads and writes on volatile variables.
Compare and Set AtomicBoolean's ValueThe method compareAndSet() allows you to compare the current value of the AtomicBoolean to an expected value, and if current value is equal to the expected value, a new value can be set on the AtomicBoolean .
compareAndset(false, true)
will return false
if the value is already true
.
It's actually equivalent to !getAndSet(true)
.
Well the text that you quoted says explicitly what the difference between the two operations is. But to make it clearer, if you ignore the atomicity aspect, the first one is equivalent to:
public void set(boolean newValue) {
this.value = newValue;
}
and the second one is equivalent to:
public boolean compareAndSet(boolean expected, boolean newValue) {
if (this.value == expected) {
this.value = newValue;
return true;
} else {
return false;
}
}
For your example, set(true)
sets the state to true
, and compareAndset(false, true)
sets the state to true
iff it is not already true
. So, yes, the net effect on the state of the AtomicBoolean
is the same.
However, you will notice that the return
value differs depending on the initial state of the AtomicBoolean
object ... so from that perspective the methods are not equivalent, even with those argument values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With