AtomicBoolean compareAndSet() method in Java with Examples
The java.util.concurrent.atomic.AtomicBoolean.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.
public final boolean compareAndSet(boolean expect, boolean val)
Parameters: The function accepts two mandatory parameters which are described below:
- expect: which specifies the value that the atomic object should be.
- val: which specifies the value to be updated if the atomic Boolean is equal to expect.
Return Value: The function returns a boolean value, it returns true on success else false.
Below programs illustrate the above function:
Previous value: false The value was updated and it is true
Previous value: true The value was updated and it is false
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.