AtomicInteger
represents an int value the can be updated AtomicInteger
is present in the java.util.concurrent.atomic
package.
The compareAndSet
method of the AtomicInteger
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(int expect, int 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.AtomicInteger;class compareSet{public static void main(String[] args) {AtomicInteger atomicInteger = new AtomicInteger(10);System.out.println("atomicInteger value : " + atomicInteger.get());int expectedValue = 5, newValue = 20;boolean isUpdated = atomicInteger.compareAndSet(expectedValue, newValue);System.out.println("compareAndSet(5, 20) is updated : " + isUpdated);System.out.println("atomicInteger : " + atomicInteger);expectedValue = 10;isUpdated = atomicInteger.compareAndSet(expectedValue, newValue);System.out.println("\ncompareAndSet(10, 20) is updated : " + isUpdated);System.out.println("atomicInteger : " + atomicInteger);}}
In line 1: We have imported the AtomicInteger
class.
In line 6: We created a new object for the AtomicInteger
class with the name atomicInteger
and the value 10
.
In line 9: We created two integer variables expectedVal
and newVal
with values 5 and 10, respectively.
In line 11: We called 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 10, and expectedVal
is 5; both values are not equal, so false
will be returned.
In line 16: We change the value of the expectedVal
variable to 10
.
In line 17: We called 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 10, and expectedVal
is 10. Both values are equal, so the newVal
(20) will be updated as the actual value, and true
is returned.