What is the AtomicInteger.getAndDecrement method in Java ?

An AtomicInteger represents an integer value that may be updated atomically.

An atomic operation is performing 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 getAndDecrement method of the AtomicInteger will atomically decrement the current value of the AtomicInteger by 1 and return the value before decrementing.

Syntax

public final int getAndDecrement()

Parameters

This method doesn’t take in any arguments.

Return value

This method returns the value of the AtomicInteger before decrementing it.

Code

The below code demonstrates how to use the getAndDecrement method.

import java.util.concurrent.atomic.AtomicInteger;
class GetAndDecrement{
public static void main(String[] args) {
AtomicInteger atomicInteger = new AtomicInteger(10);
System.out.println("The value in the atomicInteger object is " + atomicInteger.get());
System.out.println("\nCalling atomicInteger.getAndDecrement()");
int val = atomicInteger.getAndDecrement();
System.out.println("The Value Before decrementing is : " + val);
System.out.println("The Value is : " + atomicInteger.get());
}
}

Explanation

  • Line 1: We have imported the AtomicInteger class.

  • Line 4: We have created a new object for the AtomicInteger class with the name atomicInteger and with the value 10.

  • Line 9: We have called the getAndDecrement method. This method will decrement the current value (10) by 1 and return the value before decrementing it (10).

Free Resources