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.
public final int getAndDecrement()
This method doesn’t take in any arguments.
This method returns the value of the AtomicInteger
before decrementing it.
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());}}
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
).