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:
- The expected value.
- 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
AtomicLongclass. - Line 4: Created a new object for the
AtomicLongclass with the nameatomicLongand the value10. - Line 6: Created two long variables,
expectedValueandnewValue, with the values of5and10respectively. - Line 7: Called the
compareAndSetmethod withexpectedValueandnewValueas an argument. This method will check if theexpectedValuematches the actual value. In our case, the actual value is10andexpectedValueis5, both values are not equal, sofalsewill be returned. - Line 11: Change the value of the
expectedValuevariable to10. - Line 12: Called the
compareAndSetmethod withexpectedValueandnewValueas an argument. This method will check if theexpectedValuematches the actual value. In our case, the actual value is10andexpectedValueis10, both values are equal, so thenewValue(20) will be updated as the actual value andtruewill be returned.