00:00

Problem Statement

Input/Output Examples

Visual Explanation

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.

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.

Complexity Analysis

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 volatile is not enough. It makes writes visible but does not make count++ atomic.
  • Always join() before reading. Otherwise the main thread may print before the workers finish.
  • Mention LongAdder for 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.