AtomicInteger
An integer that can be changed safely from several threads without locks.
Available since: Java 1.5
Syntax
public class AtomicInteger extends NumberExamples
A request counter used by many threads:
void main() {
var requests = new AtomicInteger();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1000; i++) {
executor.submit(requests::incrementAndGet);
}
}
IO.println(requests.get());
}Output:
1000The main operations:
void main() {
var n = new AtomicInteger(5);
IO.println(n.incrementAndGet());
IO.println(n.getAndAdd(10));
IO.println(n.updateAndGet(x -> x * 2));
IO.println(n.compareAndSet(32, 0) + " " + n.get());
}Output:
6
6
32
true 0Notes
incrementAndGet() returns the new value, getAndIncrement() the old one. compareAndSet(expected, new) changes the value only if it equals the expected one. For long there is AtomicLong, and for very frequent updates from many threads LongAdder.
See also
- synchronized — Lets only one thread at a time run a block of code.
- ConcurrentHashMap — A thread-safe map for concurrent use from many threads.
- volatile — Marks a field whose changes are immediately visible to all threads.
Related recipes
In the tutorial
- Synchronization — Race conditions in Java and how to avoid them — synchronized methods and blocks, atomic classes like AtomicInteger, ReentrantLock and a shared lock object.