What is the AtomicInteger.getAndSet method in Java?

An AtomicInteger represents an integer value that may be updated atomically.

Atomic operations perform 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.

The AtomicInteger class is present in the java.util.concurrent.atomic package.

Thishttps://www.digitalocean.com/community/tutorials/atomicinteger-java article may help you get a greater understanding of the atomic concept.

The getAndSet method of the AtomicInteger class atomically updates the given value as the current value of the AtomicInteger and returns the previous value.

Syntax

public final int getAndSet(int newValue)

Parameters

This method takes the new value of the AtomicInteger object as an argument.

Return value

This method returns the previous value of the AtomicInteger.

Code

The code below demonstrates how to use the getAndSet method.

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

Explanation

  • Line 1: We import the AtomicInteger class.
  • Line 4: We create a new object for the AtomicInteger class with the name atomicInteger and with the value 10.
  • Line 9: We use the getAndSet method with 5 as an argument. This method will update the passed value (5) as the current value and return the old value (10).

Free Resources