What is the AtomicInteger.getAndIncrement() method in Java?
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 10AtomicInteger 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());}}
Explanation
-
Line 1: We import the
AtomicIntegerclass. -
Line 5: We create a new object for the
AtomicIntegerclass with the nameatomicIntegerand with the value10. -
Line 10: We call the
getAndIncrementmethod. This method increments the current value(10) by1and returns the value before incrementing(10).