Trusted answers to developer questions

What is the AtomicLong.getAndAdd method in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

AtomicLong represents a long value the 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 AtomicLong is present in the java.util.concurrent.atomic package.

This article helps you for a greater understanding of the Atomic concept.

The getAndAdd method of the AtomicLong will atomically add the given value and returns the value before adding(previous value) of the AtomicLong object.

Syntax

public final long getAndAdd(long valueToAdd)

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

This method returns the value before adding the passed value.

Code

The code below demonstrates how to use the getAndAdd method:

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

Explanation

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

In line number 4: Created a new object for the AtomicLong class with the name atomicLong 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).

RELATED TAGS

atomiclong
getandadd
java
Did you find this helpful?