What is the AtomicInteger.getAndAdd method in Java?

AtomicInteger represents an int value that may be updated atomically (Atomic operation is performing 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 is present in the java.util.concurrent.atomic package.

The getAndAdd method of the AtomicInteger will atomically add the given value and returns the current value before adding that value (in previous value) of the AtomicInteger object.

Syntax

public final int getAndAdd(int valueToAdd)

This method takes the value to be added to the current value of the AtomicInteger object as an argument.

This method returns the previous value before adding the passed value into the current value.

Code

The below code demonstrates how to use the getAndAdd method:

import java.util.concurrent.atomic.AtomicInteger;
class GetAndAdd{
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.getAndAdd(5)");
val = atomicInteger.getAndAdd(5);
System.out.println("\nThe old Value is : " + val);
System.out.println("The new Value is : " + atomicInteger.get());
}
}

Explanation

In line number 1: We have imported the AtomicInteger class.

In line number 4: Created a new object for the AtomicInteger class with the name atomicInteger and with the value 10.

In line number 9: Used the getAndAdd method with 5 as an argument. This method will add the passed value(5) to the already present value(10) and return the old value(10).

Free Resources