Java Concurrency Program · CD05
Fix a Race Condition with AtomicInteger in Java
count++ looks like one step, but it is three: read, add, write. Two threads can interleave those steps and lose updates.
Problem Statement
Two threads each increment a shared counter 1000 times. With a plain int and count++, the final value is often less than 2000.
Fix the program so that the result is always exactly 2000, and wait for both threads to finish before reading the counter.
Input/Output Examples
2 threads x 1000 incrementsOutput2000Explanation: every increment is applied exactly once.2 threads x 1000 incrementsOutput2000 or lessExplanation: lost updates make the result unpredictable.read before the threads finishOutputany valueExplanation: the main thread must wait with join().Visual Explanation
- Thread Astepsread 5add 1has 6 in a register
- Thread Bstepsread 5add 1write 6reads before A writes
- Thread Astepswrite 6overwrites B's result one update lost
- Atomic fixstepsincrementAndGetread-add-write as one step
- Done5 → 7
The problem is not that threads run in parallel, but that the read and the write can be separated by another thread's write. Both fixes make the whole read-modify-write indivisible.
Approaches
Both approaches make the increment safe. One uses a lock-free atomic class; the other uses a lock.
Approach 1: AtomicInteger (Recommended)
Idea: replace the int with an AtomicInteger and call incrementAndGet().
- Declare
AtomicInteger count. - Each thread calls
count.incrementAndGet()1000 times. - Call
join()on both threads, then readcount.get().
Time: O(n) · Space: O(1). n is the total number of increments.
Approach 2: synchronized Method
Idea: put count++ inside a synchronized method so only one thread can run it at a time.
- Declare
static synchronized void increment(). - Each thread calls it 1000 times.
- Join both threads and print the result.
Time: O(n) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: AtomicInteger (Recommended)
Uses a hardware compare-and-swap instruction, so threads never block each other.
import java.util.concurrent.atomic.AtomicInteger;
public class CounterAtomic {
// incrementAndGet() is a single atomic read-modify-write, so no update is lost
private static final AtomicInteger count = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
count.incrementAndGet();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join(); // wait for both threads before reading
t2.join();
System.out.println("2 threads x 1000 increments -> count = " + count.get());
}
}
2 threads x 1000 increments -> count = 2000
Time complexity: O(n) · Space complexity: O(1).
Approach 2: synchronized Method
A lock also guarantees that changes are visible to other threads, so the plain int is safe inside it.
public class CounterSynchronized {
private static int count = 0;
// Only one thread at a time can run this method, so count++ cannot be interleaved
private static synchronized void increment() {
count++;
}
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("2 threads x 1000 increments -> count = " + count);
}
}
2 threads x 1000 increments -> count = 2000
Time complexity: O(n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| AtomicInteger | O(n) | O(1) |
| synchronized Method | O(n) | O(1) |
Both versions perform each increment in constant time. Under heavy contention, AtomicInteger usually scales better than a lock; for very hot counters, LongAdder scales better still.
Interview Tips and Recommended Approach
- Explain why
count++is not atomic. It is read, add, write: three steps that can interleave. - Know that
volatileis not enough. It makes writes visible but does not makecount++atomic. - Always
join()before reading. Otherwise the main thread may print before the workers finish. - Mention
LongAdderfor counters that many threads update very frequently.
Recommended Approach: AtomicInteger
Why: it fixes the race without locks, is a single line to apply and is the standard tool for shared counters.