← All Exercises
Safe Increment with AtomicInteger and a Latch
advancedjava
Background
Read-modify-write on a plain int is not atomic. AtomicInteger provides lock-free increments, and a start latch maximizes contention so lost updates become visible.
Problem
Use multiple threads that each increment a shared counter 100,000 times. Synchronize their start with a latch, wait for completion, and assert the final value equals workers times increments.
Input
Optional worker count and increments per worker arguments, defaulting to 8 and 100000; both must be positive integers.
Output
A line counter=<value> expected=<value>, followed by an exception if the observed value differs from workers times increments.
Sample tests
Sample 1
Input: run with the defaults 8 workers and 100000 increments each
Expected: counter=800000 expected=800000
Sample 2
Input: run with arguments 4 100000
Expected: counter=400000 expected=400000
Your solution
Learning objective
Use atomic integers for lock-free counters, a CountDownLatch to align thread starts, and executor shutdown to observe completion.