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.
public final boolean compareAndSet(long expect, long 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, it returns false
.
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);}}
AtomicLong
class.AtomicLong
class with the name atomicLong
and the value 10
.expectedValue
and newValue
, with the values of 5
and 10
respectively.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.expectedValue
variable to 10
.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.