What is the AtomicLong.getAndDecrement method in Java?
AtomicLong represents a long value the may be updated java.util.concurrent.atomic package.
Note: You can learn more about the Atomic concept in this
. article https://www.digitalocean.com/community/tutorials/atomicinteger-java
The getAndDecrement method decrements the current value of the AtomicLong by 1 and returns the value before decrementing.
Syntax
public final long getAndDecrement()
Parameters
This method doesn’t take any argument.
Return value
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 atomicLongObj = new AtomicLong(10);System.out.println("The value in the atomicLong object is " + atomicLongObj.get());System.out.println("\nCalling atomicLongObj.getAndDecrement()");long val = atomicLongObj.getAndDecrement();System.out.println("The Value Before decrementing is : " + val);System.out.println("The Value is : " + atomicLongObj.get());}}
Explanation
Line 1: We import the AtomicLong class.
Line 4: We create a new object for the AtomicLong class with the name atomicLongObj and with the value 10.
Line 9: We call the getAndDecrement method. This method will decrement the current value (10) by 1 and returns the value before decrementing (10).