What is the AtomicLong.compareAndSet method in Java?

An atomic operation performs a single unit of work on a resource. During that operation, no other operations are allowed on the same resource until the performing operation is finished. AtomicLong represents a long value that may be updated atomically. The AtomicLong class is present in the java.util.concurrent.atomic package.

This article is helpful if you want a greater understanding of the Atomic concept.

The compareAndSet method of AtomicLong 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(long expect, long newValue)

Arguments

This method takes two arguments:

  1. The expected value.
  2. 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, it returns false.

Working example

The code below demonstrates how to use the compareAndSet method:

import java.util.concurrent.atomic.AtomicLong;
class CompareSett{
public static void main(String[] args) {
AtomicLong atomicLong = new AtomicLong(10);
System.out.println("atomicLong value = : " + atomicLong.get());
long expectedValue = 5, newValue = 20;
boolean isUpdated = atomicLong.compareAndSet(expectedValue, newValue);
System.out.println("\ncompareSet(5, 20) is updated : " + isUpdated);
System.out.println("atomicLong : " + atomicLong);
expectedValue = 10;
isUpdated = atomicLong.compareAndSet(expectedValue, newValue);
System.out.println("\ncompareSet(10, 20) is updated : " + isUpdated);
System.out.println("atomicLong : " + atomicLong);
}
}

Explanation

  • Line 1: We have imported the AtomicLong class.
  • Line 4: Created a new object for the AtomicLong class with the name atomicLong and the value 10.
  • Line 6: Created two long variables, expectedValue and newValue, with the values of 5 and 10 respectively.
  • Line 7: Called the compareAndSet method with expectedValue and newValue as an argument. This method will check if the expectedValue matches the actual value. In our case, the actual value is 10 and expectedValue is 5, both values are not equal, so false will be returned.
  • Line 11: Change the value of the expectedValue variable to 10.
  • Line 12: Called the compareAndSet method with expectedValue and newValue as an argument. This method will check if the expectedValue matches the actual value. In our case, the actual value is 10 and expectedValue is 10, both values are equal, so the newValue(20) will be updated as the actual value and true will be returned.

Free Resources