What is the AtomicInteger.compareAndSet method in Java?

AtomicInteger represents an int value the can be updated atomicallyAn atomic operation is performing a single unit of work on a resource. No other operations are allowed on the same resource until the performing operation is finished.. The 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:

  1. The expected value.
  2. 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 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.

Free Resources