What is the AtomicInteger.compareAndSet method in Java?
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.
Syntax
public final boolean compareAndSet(int expect, int newValue)
Argument
This method takes two arguments:
- The expected value.
- The new value to be updated 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.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);}}
Explanation
-
In line 1: We have imported the
AtomicIntegerclass. -
In line 6: We created a new object for the
AtomicIntegerclass with the nameatomicIntegerand the value10. -
In line 9: We created two integer variables
expectedValandnewValwith values 5 and 10, respectively. -
In line 11: We called the
compareAndGetmethod withexpectedValandnewValas arguments. This method will check if theexpectedValmatches the actual value. In our case, the actual value is 10, andexpectedValis 5; both values are not equal, sofalsewill be returned. -
In line 16: We change the value of the
expectedValvariable to10. -
In line 17: We called the
compareAndGetmethod withexpectedValandnewValas arguments. This method will check if theexpectedValmatches the actual value. In our case, the actual value is 10, andexpectedValis 10. Both values are equal, so thenewVal(20) will be updated as the actual value, andtrueis returned.