Stop 12 · Multithreading & JVM InternalsTopics · 3/9

Race Conditions & Deadlocks

Part of the Java Roadmap

In short

The two scariest concurrency bugs: one gives wrong answers only sometimes, the other freezes your app with no error at all. Knowing their shape helps you spot them in code reviews and interviews.

A race condition happens when threads read and write shared data at the same time and the result depends on timing. A deadlock happens when threads each hold a lock the other needs and wait forever.

The jaadu stands between two cars stuck bumper to bumper in a narrow old city lane, arms raised, while both drivers fold their arms and refuse to reverse.

Think of it like this

The narrow lane standoff

Two cars meet in a narrow lane in old Delhi. Each has already entered half of it, each needs the other to reverse, and neither will. Nobody moves, forever. That is a deadlock. A race condition is two shoppers grabbing the last packet of Maggi at the same moment, and the shelf count ending up wrong.

Watch it happen

How two transfers deadlock

Thread A
Account 1
Account 2
Thread B

lock

1/4Thread A moves ₹500 from account 1 to 2. It locks account 1 first.

The big ideas

What you need to know

Race condition

The result depends on timing. count++ is really read, add, write, and two threads can interleave those steps.

Check-then-act

if (!map.containsKey(k)) map.put(k, v) is a race. Use an atomic method like putIfAbsent or computeIfAbsent.

Deadlock needs a cycle

Each thread holds one lock and waits for another held by someone else. No timeout, no error, just frozen threads.

Fixed lock order

Always take locks in the same global order, for example by account id. A cycle can then never form.

See it in code

Walk through the code

java
1class Account {2    final long id;3    long balance;4    Account(long id, long balance) { this.id = id; this.balance = balance; }5}6 7class Bank {8    void transfer(Account from, Account to, long amount) {9        Account first  = from.id < to.id ? from : to;10        Account second = from.id < to.id ? to : from;11 12        synchronized (first) {13            synchronized (second) {14                if (from.balance < amount) {15                    throw new IllegalStateException("Insufficient balance");16                }17                from.balance -= amount;18                to.balance += amount;19            }20        }21    }22}

1/3Pick the lock order by id, not by which account is 'from'.

Locking both accounts in id order means two opposite transfers can never wait on each other.

Save yourself the pain

Common mistakes

Oops

Thinking a bug that appears once in a hundred runs is a flaky test.

Do this instead

Intermittent wrong totals are a classic race condition. Look for shared mutable state touched without a lock.

Oops

Locking from first, then to, in a transfer method.

Do this instead

Two opposite transfers will deadlock. Order locks by a stable key like id.

Oops

Restarting the app when it freezes and moving on.

Do this instead

Take a thread dump with jstack <pid> or jcmd <pid> Thread.print. It names the deadlocked threads and the locks they hold.

Your mission

Cause and cure a deadlock

~30 min

Quick check

Which change reliably prevents the transfer deadlock?

Go deeper

  1. 1Show a race condition with two threads incrementing a shared counter.
  2. 2Create a deadlock with two locks taken in opposite order, then fix it with a consistent lock order.
  3. 3Take a thread dump with jstack and find the deadlocked threads.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge