CKTIS / Java
AtomicLong.incrementAndGet(): Increment and return the new value
Atomically increase an `AtomicLong` counter by 1 and return the updated `long`, rather than the value before the increment.
Version: Java SE 21
Syntax
public final long incrementAndGet()
// Call on an AtomicLong instance:
long next = counter.incrementAndGet();In Java SE 21, AtomicLong.incrementAndGet() is a no-argument instance method on java.util.concurrent.atomic.AtomicLong. It adds 1 to the value stored in the object and returns the result as a primitive long. It is equivalent to addAndGet(1L).
getAndIncrement() also atomically adds 1, but returns the value before the change. With incrementAndGet(), reading, adding and writing form one atomic operation: concurrent increments of the same counter do not overwrite one another. This guarantee does not extend to surrounding code: separate get() and set() calls do not form one atomic operation.
Incrementing Long.MAX_VALUE wraps the counter to Long.MIN_VALUE. The method returns that value and does not throw an exception for overflow.
Examples
import java.util.concurrent.atomic.AtomicLong;
public class Main {
public static void main(String[] args) {
AtomicLong counter = new AtomicLong(1000L);
System.out.println(counter.incrementAndGet());
System.out.println(counter.incrementAndGet());
}
}Result
1001 1002
The counter starts at `1000L`. Two successive calls on the same object return and print `1001` and then `1002`.
Related lessons
- Java · Lesson 55 · Intermediate · Version: 2