AtomicLongArray compareAndSet() method in Java with Examples
The Java.util.concurrent.atomic.AtomicLongArray.compareAndSet() is an inbuilt method in java that atomically sets the element at a position to the given updated value if the current value is equal to the expected value. This method takes the index value, the expected value and the update value as the parameters and returns a boolean value stating if the value has been updated.
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.
public final boolean compareAndSet(int i, long expect, long update)
Parameters: The function accepts three parameters:
Return value: The function returns a boolean value stating if the value has been updated. It returns true if successful, else it returns false indicating that the current value was not equal to the expected value.
Below programs illustrate the above method:
The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 40, 5]
The array : [1, 2, 3, 4, 5] The array after update : [1, 2, 3, 4, 5]