What is the AtomicInteger.addAndGet method in Java?

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

An atomic operation is one that performs a single unit of work on a resource. During that operation, no other operations are allowed access to the same resource until the performing operation is finished.

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

The addAndGet method of the AtomicInteger will atomically add the given value to the current value of the AtomicInteger object and then return the updated value.

Syntax

public final int addAndGet(int valueToAdd)

Parameters

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

Return value

This method returns an integer value after atomically adding the passed value.

Code

The code below demonstrates how to use the addAndGet method.

import java.util.concurrent.atomic.AtomicInteger;
class AddAndGet{
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.addAndGet(5)");
val = atomicInteger.addAndGet(5);
System.out.println("\nThe value in the atomicInteger object is " + atomicInteger.get());
}
}

Explanation

In line 1: We import the AtomicInteger class.

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

In line 9: We use 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 new value 15.