AtomicBoolean
represents a boolean value that can be updated AtomicBoolean
is present in the java.util.concurrent.atomic
package.
The compareAndSet
method of AtomicBoolean
will atomically set the given value as the current value if the already present value is equal to the expected value.
public final boolean compareAndSet(boolean expect, boolean newValue)
This method takes two arguments:
This method returns true
if the current value is equal to the expected value and the new value is updated. Otherwise, false
will be returned.
The below code demonstrates how to use the compareAndSet
method.
import java.util.concurrent.atomic.AtomicBoolean;class compareSet{public static void main(String[] args) {AtomicBoolean atomicBoolean = new AtomicBoolean(false);System.out.println("atomicBoolean value : " + atomicBoolean.get());boolean expectedValue = true, newValue = true;boolean isUpdated = atomicBoolean.compareAndSet(expectedValue, newValue);System.out.println("compareAndSet(true, true) is updated : " + isUpdated);System.out.println("\natomicBoolean value: " + atomicBoolean);expectedValue = false;isUpdated = atomicBoolean.compareAndSet(expectedValue, newValue);System.out.println("compareAndSet(false, true) is updated : " + isUpdated);System.out.println("atomicBoolean value: " + atomicBoolean);}}
Line 1: We import the AtomicBoolean
class.
Line 6: We create a new object for the AtomicBoolean
class with the name atomicBoolean
and the value false
.
Line 9: We create two boolean variables expectedVal
and newVal
, with values true
and true
, respectively.
Line 11: We call the compareAndGet
method with expectedVal
and newVal
as arguments. This method will check if the expectedVal
matches the actual value. In our case, the actual value is false
, and expectedVal
is true
. Both values are not equal, so false
will be returned.
Line 16: We change the value of the expectedVal
variable to false
.
Line 17: We call the compareAndGet
method with expectedVal
and newVal
as arguments. This method will check if the expectedVal
matches the actual value. In our case, the actual value is false
, and expectedVal
is false
. Both values are equal, so the newVal
(true) will be updated as the actual value, and true
will be returned.