AtomicIntegerArray gives every index its own lock-free counter, so two threads bumping different (or the same) slots never lose an update. The final totals only depend on how many times each slot was incremented, not on thread scheduling.
AtomicIntegerArray counts = new AtomicIntegerArray(3);
Runnable bump = () -> {
for (int i = 0; i < 1000; i++) counts.incrementAndGet(i % 3);
};
Thread t1 = new Thread(bump);
Thread t2 = new Thread(bump);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Slot 0: " + counts.get(0));
System.out.println("Slot 1: " + counts.get(1));
System.out.println("Slot 2: " + counts.get(2));
Slot 0: 668
Slot 1: 666
Slot 2: 666
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27