CKTIS / Java
AtomicInteger: read, increment, reset, and retry with CAS
Initialize an atomic counter, read or replace its value, and increment it in one operation. Use a compare-and-set loop to retry a conditional update after a mismatch.
Version: Java SE 21
Syntax
import java.util.concurrent.atomic.AtomicInteger;
AtomicInteger counter = new AtomicInteger(initialValue);
int current = counter.get();
boolean changed = counter.compareAndSet(expectedValue, newValue);
int updated = counter.incrementAndGet();
counter.set(newValue);
// initialValue, expectedValue, and newValue are int values.AtomicInteger in java.util.concurrent.atomic holds one mutable int. The AtomicInteger(int) constructor sets its initial value. AtomicInteger.get returns the current int without changing it. AtomicInteger.set unconditionally replaces the value and returns nothing (void). These methods have volatile read and write semantics, respectively. Calling set(0) resets the same counter.
AtomicInteger.incrementAndGet atomically adds 1 and returns the new int; getAndIncrement() returns the previous value. For a simple increment, use incrementAndGet() rather than set(get() + 1): another update can occur between the separate read and write and be overwritten. A read followed by a reset is not one atomic operation either.
In a CAS retry loop, read with get(), compute a replacement, then call compareAndSet(int expectedValue, int newValue). The method atomically checks whether the current value equals expectedValue. If it does, the method writes newValue and returns true; otherwise it returns false without writing. On false, read again and recompute before retrying. On true, exit the loop. CAS checks the current value, not its change history.
Examples
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounterDemo {
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger(0);
for (int i = 0; i < 3; i++) {
counter.incrementAndGet();
}
System.out.println(counter.get());
counter.set(0);
int expected = counter.get();
System.out.println(expected);
for (int i = 0; i < 5; i++) {
counter.incrementAndGet();
}
System.out.println(counter.get());
// The first CAS still expects the value read just after the reset.
while (!counter.compareAndSet(expected, expected + 2)) {
System.out.println("CAS retry");
expected = counter.get();
}
System.out.println(counter.get());
}
}Result
3 0 5 CAS retry 7
The counter goes through `0 → 3 → 0 → 5`. The first CAS expects `0` but finds `5`, so the program prints `CAS retry`. After reading again, CAS writes `7`. Everything runs on one thread.
Related lessons
- Java · Lesson 32 · Advanced · Version: 2
- Java · Lesson 55 · Intermediate · Version: 2