AtomicLong represents a long 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 AtomicLong is present in the java.util.concurrent.atomic package.
The decrementAndGet method of the AtomicLong atomically decrements the current value by one and returns the updated value of the AtomicLong object.
public final long decrementAndGet()
This method doesn’t take any argument.
This method returns the decremented value as a long value.
The code below demonstrates how to use the decrementAndGet method:
import java.util.concurrent.atomic.AtomicLong;class DecrementAndGet{public static void main(String[] args) {// initial value is 10AtomicLong atomicLong = new AtomicLong(10);System.out.println("The initial value in the AtomicLong object is: " + atomicLong.get());// Calling atomicLong.decrementAndGet()long val = atomicLong.decrementAndGet();// updated value will be 9System.out.println("The new value in the AtomicLong object is: " + val);}}
Line 1: We import the AtomicLong class.
Line 5: We create a new object for the AtomicLong class with the name atomicLong and with the value 10.
Line 10: We call the decrementAndGet method. This method decrements the current value(10) by 1 and returns the new value(9).