Concurrency Issues: Avoiding the Crash

Concurrency Issues: Avoiding the Crash in Java: A small airline has one seat left on tonight's flight: 14A.

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.

StepThread AThread Bcount
1read count -> 00
2read count -> 00
3add 1 -> 10
4write 11
5add 1 -> 11
6write 11

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.

ProblemWhat goes wrongStandard fix
Race conditionInterleaved read-modify-write loses updatessynchronized, AtomicInteger, a Lock
Stale read (visibility)A thread keeps seeing an old cached valuevolatile, or any synchronization's happens-before
ConcurrentModificationExceptionA collection is structurally changed mid-iterationA concurrent collection, or iterate a copy
DeadlockTwo threads each hold the lock the other needsOne consistent lock order; tryLock with timeout
StarvationA thread never gets its turn at a lock or CPUFair 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

  1. 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.
  1. Using volatile to fix a counter. volatile guarantees visibility, not atomicity. A volatile int still races on count++, because the read and the write are still separate steps. For an atomic counter you need AtomicInteger or a lock.
  1. 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.
  1. Guarding the same data with different locks. If two threads synchronized on 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.
  1. ConcurrentModificationException from editing while iterating. Removing from an ArrayList during a for-each -- even on one thread -- throws it, and across threads it is worse. Use a concurrent collection or iterate over a copy.
  1. 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 as putIfAbsent or computeIfAbsent.
  1. 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 tryLock with a timeout to break the cycle.
  1. Holding a lock during slow work. Doing I/O or a long computation inside a synchronized block makes every other thread queue behind it, destroying throughput and inviting liveness problems. Keep critical sections tiny.
  1. Sharing a non-thread-safe object across threads. A plain HashMap, ArrayList, or SimpleDateFormat used 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 LongAdder does internally.
  • Match the tool to the problem. AtomicInteger or LongAdder for counters, ConcurrentHashMap for shared maps, volatile for a simple flag, and synchronized or a Lock when several changes must happen together. Do not reach for volatile where you needed atomicity.
  • Make compound actions genuinely atomic. When a check must bind to its action, do it in one step -- putIfAbsent, compute, a compareAndSet loop, 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 tryLock with a timeout where you need to recover rather than hang.
  • Reach for java.util.concurrent first. ExecutorService, BlockingQueue, ConcurrentHashMap, and the atomic classes are battle-tested and almost always better than hand-rolled synchronized/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

  1. The Concurrent Exception: Iterate an ArrayList with a for-each loop while removing an element mid-iteration, and observe the ConcurrentModificationException. Then switch to a CopyOnWriteArrayList and note both that the crash disappears and what that collection trades away (a fresh copy on every write).
  1. Volatile: Research volatile. Use it on a boolean running flag 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 make count++ safe -- the difference between visibility and atomicity.
  1. Atomic Classes: Look up AtomicInteger. Compare incrementAndGet() with a synchronized method wrapping count++: both give the correct total, but explain how AtomicInteger achieves 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.