CKTIS / Java
AtomicLong — an atomic long counter
AtomicLong holds one long value and provides atomic updates shared by threads. Its incrementAndGet() method increases the value by one and returns the updated result.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
AtomicLong counter = new AtomicLong(0L);
long updated = counter.incrementAndGet();java.util.concurrent.atomic.AtomicLong is a mutable object holding a single long value. It suits shared counters and sequence numbers. The constructor new AtomicLong() initially sets zero; new AtomicLong(0L) specifies that value explicitly. It is not a replacement for an immutable Long object.
AtomicLong.incrementAndGet() performs the read, increment by one, and write as one atomic operation, then returns the updated long value. In contrast, getAndIncrement() returns the value before the increment. get() reads the current value.
Atomicity of an individual method does not cover an arbitrary sequence of calls: counter.set(counter.get() + 1) is not an atomic increment. Another thread can change the counter between the read and write. Use counter.incrementAndGet() for that update; the counter alone also does not protect invariants involving several variables.
In the example, two threads each increment the same counter 1000 times. Both join() calls precede reading the result, so thread execution order does not change the expected output 2000. Documentation scope: Java SE 21; the repository runtime and production runtime are not attested.
Examples
import java.util.concurrent.atomic.AtomicLong;
public class Main {
public static void main(String[] args) throws InterruptedException {
AtomicLong counter = new AtomicLong(0L);
Runnable work = () -> {
for (int i = 0; i < 1000; i++) {
counter.incrementAndGet();
}
};
Thread first = new Thread(work);
Thread second = new Thread(work);
first.start();
second.start();
first.join();
second.join();
System.out.println(counter.get());
}
}Result
2000
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.