The Analogy:
A small airline has one seat left on tonight's flight: 14A. Two booking clerks, Ada and Ben, share a single seat map, and right now each has a customer at the desk who wants that last seat. Ada glances at the map: 14A is free. A heartbeat later, before Ada has written anything, Ben glances at the same map: 14A is free. Both clerks, each acting correctly on what they saw, sell 14A. Ada writes "14A: Alice." Ben writes "14A: Bob." The map now says Bob, Alice's sale has silently vanished, and two passengers are holding a boarding pass for one seat.
Neither clerk did anything wrong on their own. The fault is that "check the seat, then sell it" was allowed to split apart -- Ben squeezed his read in between Ada's read and Ada's write. This is a race condition: the outcome depends entirely on the precise timing of who reads and who writes when. In a Java counter it is the exact same story. count++ looks like one action but is really three -- read count, add one, write it back -- and if two threads interleave those steps, one thread's write lands on a value the other has already made stale, and an update is lost.
What makes race conditions so dangerous is precisely that timing. The bug does not announce itself. On a quiet developer laptop the two clerks almost never collide, so every test passes; under production load, with the desks slammed, they collide constantly. And the corruption is different every time -- lose one update, lose forty, lose none on the next run -- so you cannot even reproduce it reliably to debug it. Non-determinism is not a side effect of the bug; it is the bug.
The cure is to make "check-and-sell" a single, indivisible step that no one can interrupt. Give the clerks one pen that must be held to both read and update the seat: whoever holds it finishes their check-and-sell before anyone else can look. In Java that indivisible step is a lock (synchronized) or an atomic operation (AtomicInteger). Without it, no amount of care inside each thread saves you, because the danger lives in the gap between their steps, not in the steps themselves.
Syntax or Core Structure
public class SafeCounter {
private int count = 0;
public synchronized void increment() { count++; } // now one indivisible step
public int get() { return count; }
public static void main(String[] args) throws InterruptedException {
SafeCounter c = new SafeCounter();
Runnable job = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread t1 = new Thread(job);
Thread t2 = new Thread(job);
t1.start(); t2.start();
t1.join(); t2.join(); // wait for both before reading the result
System.out.println("final count: " + c.get());
}
}
Output:
final count: 2000
This prints 2000 on every run, on every machine, because synchronized forces the two threads to take turns inside increment() and join() guarantees both have finished before get() runs. Remove the synchronized keyword and the same program prints some number below 2000 -- 1997 one run, 1834 the next, 1200 the one after -- because count++ can now interleave and lose updates. That broken output is deliberately not shown as a fixed value here: it has no single correct answer, and that unpredictability is exactly the defect.
Technical Depth:
Why count++ Is Not One Step
The whole race hinges on count++ being three operations wearing the disguise of one: read the current value, add one, write the sum back. Between any two of those, the scheduler may switch to another thread. The table traces one possible interleaving of two threads each doing a single count++ starting from 0 -- the classic lost update.
| Step | Thread A | Thread B | count |
|---|---|---|---|
| 1 | read count -> 0 | 0 | |
| 2 | read count -> 0 | 0 | |
| 3 | add 1 -> 1 | 0 | |
| 4 | write 1 | 1 | |
| 5 | add 1 -> 1 | 1 | |
| 6 | write 1 | 1 |
Two increments ran, yet count ends at 1, not 2. Thread B read 0 before Thread A had written its 1, so B's write overwrote A's with the same value. synchronized fixes this by making a thread finish all three steps -- and release the lock -- before the other may enter, so the reads can never straddle each other's writes.
The Family Of Concurrency Bugs And Their Tools
"Concurrency issue" is an umbrella over several distinct failures, and each has its own standard fix -- reaching for the wrong one leaves the bug in place. A crucial pairing: volatile fixes visibility (making one thread's write visible to others) but does nothing for atomicity, so a volatile int still races on count++. Match the tool to the actual problem.
| Problem | What goes wrong | Standard fix |
|---|---|---|
| Race condition | Interleaved read-modify-write loses updates | synchronized, AtomicInteger, a Lock |
| Stale read (visibility) | A thread keeps seeing an old cached value | volatile, or any synchronization's happens-before |
ConcurrentModificationException | A collection is structurally changed mid-iteration | A concurrent collection, or iterate a copy |
| Deadlock | Two threads each hold the lock the other needs | One consistent lock order; tryLock with timeout |
| Starvation | A thread never gets its turn at a lock or CPU | Fair locks; do not lean on priority |
Notice that synchronized quietly solves two rows at once: it makes the guarded operation atomic and establishes a happens-before edge, so it fixes both the race and the visibility problem for the data it guards. That two-for-one is why a single well-placed lock is often simpler to reason about than scattering volatile and atomics around.
Visibility: The volatile Stop Flag
The visibility row deserves a concrete look, because it is the concurrency bug that is not about interleaving. When one thread writes a plain field and another reads it, the JVM does not promise the reader ever sees the new value -- the reader may keep using a cached copy indefinitely. The canonical victim is a "stop" flag: one thread flips running to false, but the worker's loop, having cached true, spins forever. volatile closes that gap by forcing every read to come from, and every write to go to, main memory.
public class StopFlag {
static volatile boolean running = true; // volatile: writes are seen by other threads
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (running) { /* spin, checking the shared flag */ }
System.out.println("worker saw the stop signal");
});
worker.start();
Thread.sleep(50); // let the worker spin a while
running = false; // ask it to stop; volatile makes this visible
worker.join();
System.out.println("done");
}
}
Output:
worker saw the stop signal
done
Because running is volatile, the worker is guaranteed to observe the false and leave its loop, so the program always ends. Drop the volatile and the worker may never see the change and spin forever -- a hang, not a crash, which is harder to diagnose. The output order is fixed: join() makes main wait for the worker's line before printing done. Note that volatile only made the flag visible; it would still not make count++ atomic, which is the distinction between the two guarantees.
Real World Example:
import java.util.concurrent.atomic.AtomicInteger;
public class RequestMeter {
// Shared across every worker; AtomicInteger makes the increment atomic without a lock.
static final AtomicInteger handled = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
int workers = 4;
int perWorker = 500;
Thread[] pool = new Thread[workers];
for (int w = 0; w < workers; w++) {
pool[w] = new Thread(() -> {
for (int i = 0; i < perWorker; i++) {
handled.incrementAndGet(); // atomic read-modify-write
}
});
}
for (Thread t : pool) t.start();
for (Thread t : pool) t.join(); // wait for all workers before reading
System.out.println("workers: " + workers);
System.out.println("per each: " + perWorker);
System.out.println("handled: " + handled.get());
}
}
Output:
workers: 4
per each: 500
handled: 2000
This is the everyday version of the counter problem: four worker threads each record 500 handled requests into one shared meter. The result is 4 times 500 -- exactly 2000 -- on every single run, no matter how the four threads interleave, because incrementAndGet() is atomic and the join() loop guarantees all four have finished before handled.get() is read. Had this used a plain int handled with handled++, the output would be some unpredictable number below 2000, and the meter would silently undercount traffic in production.
The reason AtomicInteger fits better than synchronized for a lone counter is that it is lock-free. Under the hood incrementAndGet() uses a CPU compare-and-swap instruction: read the value, and write the new one only if no one changed it in between, retrying if they did. There is no lock to acquire, no thread ever blocks, and under heavy contention that scales far better than every thread queueing for one synchronized monitor. For a single independent value, it is the right instrument.
The honest limits matter here. AtomicInteger makes one operation atomic and nothing more -- the moment you need two things to change together, or a check to bind to its action, it stops being enough. The classic trap is if (handled.get() < limit) handled.incrementAndGet();: two atomic calls are not one atomic step, so two threads can both pass the check and both increment past the limit. That needs a compareAndSet loop or a lock. There is also a scaling flaw hiding in plain sight: a single global counter every thread hammers is a contention hot spot, and at very high throughput even lock-free CAS retries pile up. The purpose-built fix is LongAdder, which keeps a private cell per thread and sums them only when you read -- trading exact-at-every-instant reads for far less contention. Knowing when AtomicInteger is no longer the answer is as important as knowing to reach for it.
Common Mistakes
- Assuming
count++is atomic. It is three operations -- read, add, write -- and two threads can interleave them and lose updates. Any unguarded read-modify-write on shared state is a race, however innocent the single line looks.
- Using
volatileto fix a counter.volatileguarantees visibility, not atomicity. Avolatile intstill races oncount++, because the read and the write are still separate steps. For an atomic counter you needAtomicIntegeror a lock.
- Trusting "it worked on my machine". Races are timing-dependent and stay hidden on a quiet, single-core-ish workload, then surface under production load or on different hardware. A passing run proves nothing about thread safety.
- Guarding the same data with different locks. If two threads
synchronizedon different objects while touching the same field, they are not mutually excluded at all -- each holds a lock the other ignores. Shared data needs one agreed lock.
ConcurrentModificationExceptionfrom editing while iterating. Removing from anArrayListduring a for-each -- even on one thread -- throws it, and across threads it is worse. Use a concurrent collection or iterate over a copy.
- Check-then-act on a concurrent collection.
if (!map.containsKey(k)) map.put(k, v)is two operations, so two threads can both pass the check and both put. Use one atomic call such asputIfAbsentorcomputeIfAbsent.
- Deadlock from inconsistent lock order. Thread 1 locks A then B while thread 2 locks B then A, and both wait forever. Always acquire multiple locks in one fixed global order, or use
tryLockwith a timeout to break the cycle.
- Holding a lock during slow work. Doing I/O or a long computation inside a
synchronizedblock makes every other thread queue behind it, destroying throughput and inviting liveness problems. Keep critical sections tiny.
- Sharing a non-thread-safe object across threads. A plain
HashMap,ArrayList, orSimpleDateFormatused by multiple threads corrupts silently. Either confine it to one thread, guard every access, or use a thread-safe alternative.
Best Practices
- Prefer immutability. Data that cannot change after construction is automatically safe for any number of threads to read. Make fields
final, return copies, and you delete whole classes of concurrency bug before they exist.
- Do not share mutable state if you can avoid it. The cheapest thread-safe design is one where threads do not touch the same data at all -- give each its own working copy and combine the results at the end, as
LongAdderdoes internally.
- Match the tool to the problem.
AtomicIntegerorLongAdderfor counters,ConcurrentHashMapfor shared maps,volatilefor a simple flag, andsynchronizedor aLockwhen several changes must happen together. Do not reach forvolatilewhere you needed atomicity.
- Make compound actions genuinely atomic. When a check must bind to its action, do it in one step --
putIfAbsent,compute, acompareAndSetloop, or a single lock held across the whole check-and-act -- never two separate atomic calls.
- Guard shared data with one documented lock, briefly. Decide which lock protects which data, write it down, and keep the critical section as small as possible so contention stays low.
- Impose a global lock order. When code must hold more than one lock, always take them in the same order everywhere to make deadlock impossible, and prefer
tryLockwith a timeout where you need to recover rather than hang.
- Reach for
java.util.concurrentfirst.ExecutorService,BlockingQueue,ConcurrentHashMap, and the atomic classes are battle-tested and almost always better than hand-rolledsynchronized/wait/notify. Rolling your own coordination is a last resort.
- Test under real contention. Stress the code with many threads and high iteration counts, run it repeatedly, and use static analysis or race detectors. A single quiet execution is not evidence of correctness for concurrent code.
Practice Exercises
- The Concurrent Exception: Iterate an
ArrayListwith a for-each loop while removing an element mid-iteration, and observe theConcurrentModificationException. Then switch to aCopyOnWriteArrayListand note both that the crash disappears and what that collection trades away (a fresh copy on every write).
- Volatile: Research
volatile. Use it on aboolean runningflag that one thread flips to stop another, and confirm the loop actually notices the change. Then explain, in a comment, why the very same keyword does not makecount++safe -- the difference between visibility and atomicity.
- Atomic Classes: Look up
AtomicInteger. CompareincrementAndGet()with asynchronizedmethod wrappingcount++: both give the correct total, but explain howAtomicIntegerachieves it lock-free with compare-and-swap, and name one situation (a compound update of two fields) where you would still need a lock instead.