AtomicInteger weakCompareAndSet() method in Java with examples
The java.util.concurrent.atomic.AtomicInteger.weakCompareAndSet() 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 weakCompareAndSet(int expect, int val)
Parameters: The function accepts two mandatory parameters which are described below:
- expect: specifies the value that the atomic object should be.
- val: specifies the value to be updated if the atomic integer is equal to expect.
Return value: The function returns a boolean value, it returns true on success else false.
Program below demonstrates the function:
Previous value: 0 The value was updated and it is 6
Previous value: 0 The value was not updated