What is the AtomicLong.getAndDecrement method in Java?

AtomicLong represents a long value the may be updated atomicallyAtomic 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 getAndDecrement method of the AtomicLong will atomically decrement the current value of the AtomicLong by 1 and returns the value before decrementing.

Syntax

public final long getAndDecrement()

This method doesn’t take any argument.

This method returns the value before decrementing it.

Code

The code below demonstrates how to use the getAndDecrement method:

import java.util.concurrent.atomic.AtomicLong;
class GetAndDecrement{
public static void main(String[] args) {
AtomicLong atomicLong = new AtomicLong(10);
System.out.println("The value in the atomicLong object is " + atomicLong.get());
System.out.println("\nCalling atomicLong.getAndDecrement()");
long val = atomicLong.getAndDecrement();
System.out.println("The Value Before decrementing is : " + val);
System.out.println("The 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: Called the getAndDecrement method. This method will decrement the current value(10) by 1 and returns the value before decrementing(10).