What is the AtomicLong.incrementAndGet method in Java?
AtomicLong represents a long value that may be updated atomically. An atomic operation performs 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. AtomicLong is present in the java.util.concurrent.atomic package.
The incrementAndGet method of AtomicLong automatically increments the current value by 1 and returns the updated value of the AtomicLong object.
Syntax
public final long incrementAndGet()
Parameters
This method doesn’t take an argument.
Return value
This method returns the incremented value as a long.
Code
The code below demonstrates how to use the incrementAndGet method.
import java.util.concurrent.atomic.AtomicLong;class IncrementAndGet{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.incrementAndGet()");long val = atomicLong.incrementAndGet();System.out.println("The new Value is : " + val);}}
Explanation
-
Line 1: We import the
AtomicLongclass. -
Line 4: We create a new object for the
AtomicLongclass with the nameatomicLongand value10. -
Line 9: We call the
incrementAndGetmethod. This method increments the current value (10) by1and returns the new value (11).