Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the AtomicInteger.addAndGet method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}
Example code for addAndGet method

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring