SteelReed

Search

Search posts, questions…

3. Advanced Java

Race conditions, volatile and deadlocks: three bugs when threads share data

Why counters drift, stop flags do nothing and requests hang when threads share state; how to choose between atomics, locks, volatile and the database; and how to review concurrent code written by AI.

17 Nov 20269 min readMid

–

1. The problem

A flash sale has 100 items left and 10,000 buy requests arrive at once on 16 threads. By evening the system has recorded 114 sold, stock at -14. No exception was thrown, and every single-threaded test is still green.

2. Key idea

A line of code looks like one step but is really several. When another thread cuts in between, the result is wrong. Go, Node.js and databases hit exactly the same thing.

2.1 What do the three bugs look like?

Bug Symptom Root cause
Race condition counters drift, stock oversold a read-modify-write or check-then-act gets interleaved
Visibility the stop flag is off but the worker keeps running no happens-before edge, so the JIT and CPU keep an old copy
Deadlock CPU near zero while requests hang two threads hold locks and wait for each other's

2.2 Which tool do I pick?

Pick the weakest tool that is enough: don't share → atomic → lock → database.

Tool Use when Don't use when
Don't share (per-thread data, immutable objects) always try first
AtomicInteger (CAS: compare-and-swap) one variable: a counter, a flag two variables must change together
LongAdder lots of threads adding (metrics) you need "if there's stock, take one"
Lock (synchronized, ReentrantLock) several variables, check-then-act you're calling I/O or HTTP
volatile a flag written by one thread counters: it guarantees visibility, not atomicity
Database (UPDATE ... WHERE stock > 0) several instances

2.3 How do I avoid deadlock?

  • One piece of state, one lock, on every read and write.
  • Lock in a fixed order, for example smaller id first. No cycle can form.
  • Or tryLock with a timeout: if you can't get every lock, release them all, wait a random moment and retry.
  • jstack <pid> prints Found one Java-level deadlock for you.

3. In Java

Each bug has a standard tool.

JAVA
// 4 threads, 1,000,000 times each
unsafeCount++;                // 1252965 (a different number every run)
atomic.incrementAndGet();     // 4000000
 
// check-then-act: one lock around the whole thing
synchronized boolean buy() {
    if (left == 0) return false;
    left--;                   // 10,000 requests, 16 threads: sold=100
    return true;
}
 
static volatile boolean running = true;   // without volatile the worker may spin forever
 
// two locks: always lock the smaller id first
Account first = from.id < to.id ? from : to;
Account second = first == from ? to : from;
synchronized (first) { synchronized (second) { /* transfer */ } }

Other languages: Go has sync.Mutex, sync/atomic, go test -race; C# has lock, Interlocked.

Why the loop never stops without volatile

Without volatile, the JIT may hoist the read of running out of the loop and turn it into while (true). The Java Memory Model only guarantees thread B sees A's write when there is a happens-before edge. Three edges you use all the time:

  • unlock happens-before the next lock on the same monitor.
  • A volatile write happens-before every later read of that variable.
  • Everything before t.start() is visible inside t; everything t did is visible after t.join().

The relation is transitive: write config, then write volatile ready = true, and any thread that sees ready == true also sees the new config. Double-checked locking for a singleton needs volatile for the same reason.

Several instances: JVM locks stop helping

synchronized only locks within one process; two pods means two separate locks. A shared invariant has to live in the database:

SQL
UPDATE product SET stock = stock - 1 WHERE id = ? AND stock > 0;  -- 0 rows: sold out

A database deadlock (two transactions locking rows in opposite order) is detected by the DB, which aborts one side. The prevention is identical: update rows in a fixed order. See Optimistic or pessimistic locking.

4. Working with AI

Hand to AI: writing concurrent tests (16 threads, a CountDownLatch), summarising a long thread dump.

Check in AI-written code:

  • Each piece of shared state is guarded by exactly one lock or one atomic.
  • No get() followed by a separate decrementAndGet(): each step is atomic, the pair is not.
  • volatile sits only on flags, never on counters.
  • Two or more locks are always taken in a fixed order; no I/O while holding a lock.
  • With several instances the invariant lives in the database, and a concurrent test proves it.

5. Exercises

Exercise 1: Review the buy() an AI wrote

The AI wrote this and said "thread-safe because it uses AtomicInteger". Find the bug, name a test that proves it, fix it.

JAVA
boolean buy() {
    if (left.get() > 0) {
        sleepQuietly();               // a bit of work between check and act
        left.decrementAndGet();
        return true;
    }
    return false;
}
Solution to Exercise 1

The bug: get() and decrementAndGet() are separate. Each step is atomic; the check-then-act as a whole is not. Test: 10,000 requests on 16 threads gives sold=114 left=-14.

Fix it with a CAS loop (or synchronized as in section 3):

JAVA
boolean buy() {
    while (true) {
        int current = left.get();
        if (current == 0) return false;
        if (left.compareAndSet(current, current - 1)) return true;
    }
}
// sold=100 left=0

With several instances, decrement stock with UPDATE ... WHERE stock > 0 and check the affected row count.

Exercise 2: Read an incident

After a deploy, checkout times out. CPU 3%, BLOCKED threads go from 4 to 180 in 10 minutes. Two thread dumps 5 seconds apart are identical and both contain Found one Java-level deadlock:. Diagnose it, say what you do in the next 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Deadlock: the two dumps are identical (no progress) and the JVM has already reported it. Heavy lock contention would show different dumps, with requests still trickling through.
  • 15 minutes: save the thread dumps as evidence, roll back the deploy or restart to save traffic.
  • Root fix: read which thread holds which lock at which line. Find the place in the new diff that takes two locks in opposite order and switch to a fixed order.

Summary

  • count++ is three steps, read-add-write; a thread cutting in between loses an update.
  • Fix a race by making "check, then act" one step: an atomic, a lock, or a conditional UPDATE.
  • volatile guarantees visibility, not atomicity.
  • Avoid deadlock: lock in a fixed order, or tryLock with a timeout.
  • A JVM lock protects nothing across several instances.

Further reading: Reviewing AI-written code.

Practice interview questions on this topic

All Concurrency questions →

Loading comments…