What is the AtomicBoolean.compareAndSet() method in Java?
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.
Syntax
public final boolean compareAndSet(boolean expect, boolean newValue)
Argument
This method takes two arguments:
- The expected value.
- The new updated value if the current value matches the expected value.
Return value
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.
Code
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);}}
Explanation
-
Line 1: We import the
AtomicBooleanclass. -
Line 6: We create a new object for the
AtomicBooleanclass with the nameatomicBooleanand the valuefalse. -
Line 9: We create two boolean variables
expectedValandnewVal, with valuestrueandtrue, respectively. -
Line 11: We call the
compareAndGetmethod withexpectedValandnewValas arguments. This method will check if theexpectedValmatches the actual value. In our case, the actual value isfalse, andexpectedValistrue. Both values are not equal, sofalsewill be returned. -
Line 16: We change the value of the
expectedValvariable tofalse. -
Line 17: We call the
compareAndGetmethod withexpectedValandnewValas arguments. This method will check if theexpectedValmatches the actual value. In our case, the actual value isfalse, andexpectedValisfalse. Both values are equal, so thenewVal(true) will be updated as the actual value, andtruewill be returned.