What is the AtomicLong.getAndSet method in Java ?

AtomicLong represents a long value the may be updated automicallyAn atomic operation performs a single unit of work on a resource. No other operations are allowed on the same resource until the performing operation is complete.. It is present in the java.util.concurrent.atomic package.

This articlehttps://www.journaldev.com/1095/atomicinteger-java may help us gain further understanding of the atomic concept.

The getAndSet method of the AtomicLong atomically updates the given value as the current value of the AtomicLong, and returns the value before updating (previous value).

Syntax

public final long getAndSet(long newValue)

This method takes the new value to be updated as the current value of the AtomicLong object as an argument.

This method returns the value before updating the passed value.

Code

The code below demonstrates how to use the getAndSet method:

import java.util.concurrent.atomic.AtomicLong;
class GetAndSet{
public static void main(String[] args) {
AtomicLong atomicLong = new AtomicLong(10);
long val = atomicLong.get();
System.out.println("The value in the atomicLong object is " + val);
System.out.println("\nCalling atomicLong.getAndSet(5)");
val = atomicLong.getAndSet(5);
System.out.println("\nThe old Value is : " + val);
System.out.println("The new Value is : " + atomicLong.get());
}
}

Explanation

Line 1: We import the AtomicLong class.

Line 4: We create a new object for the AtomicLong class with the name atomicLong, and the value 10.

Line 9: We use the getAndSet method with 5 as an argument. This method updates the passed value(5) as the current value, and returns the old value(10).

Free Resources