What is the AtomicLong.addAndGet method in Java ?

AtomicLong represents a long value that may be updated atomicallyAtomic 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 AtomicLong class is present in the java.util.concurrent.atomic package.

Syntax

public final long addAndGet(long valueToAdd)

The addAndGet() method of the AtomicLong class takes the value to be added and will atomically add this value to the current value of the AtomicLong object and return the updated value.

Code

The below code demonstrates how to use the addAndGet() method:

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

Explanation

In line 1: We imported the AtomicLong class.

In line 4: We created a new object for the AtomicLong class with the name atomicLong and with the value 10.

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

Free Resources