Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
atomicinteger
communitycreator

What is the AtomicInteger.getAndIncrement() 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.

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 getAndIncrement method of the AtomicInteger atomically increments the current value of the AtomicInteger by one and returns the value before incrementing.

Syntax

public final int getAndIncrement()

Parameter

This method doesn’t take any argument.

Return value

This method returns the int value before incrementing it.

Code

The code below demonstrates how to use the getAndIncrement method:

import java.util.concurrent.atomic.AtomicInteger;
class GetAndIncrement{
public static void main(String[] args) {
// initial value is 10
AtomicInteger atomicInteger = new AtomicInteger(10);
System.out.println("The initial value in the atomicInteger object is: " + atomicInteger.get());
// Calling atomicInteger.getAndIncrement();
int val = atomicInteger.getAndIncrement();
System.out.println("The value before incrementing is: " + val);
System.out.println("The new value is: " + atomicInteger.get());
}
}
Using the AtomicInteger.getAndIncrement() method in Java

Explanation

  • Line 1: We import the AtomicInteger class.

  • Line 5: We create a new object for the AtomicInteger class with the name atomicInteger and with the value 10.

  • Line 10: We call the getAndIncrement method. This method increments the current value(10) by 1 and returns the value before incrementing(10).

RELATED TAGS

java
atomicinteger
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