Skip to lesson

Concurrency bugs: common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most concurrency bugs found in code reviews and interviews follow a few patterns: two locks taken in opposite orders, a rule checked in one step and acted on in another, and an unsafe read-modify-write. Once you can name the pattern, the fix follows.

Find the deadlock: locks hidden inside method calls

A real deadlock rarely looks like two nested synchronized blocks in one method. More often each class looks correct on its own: a synchronized method of Customer calls a synchronized method of Store, while a synchronized method of Store calls back into Customer.

Example 1 · A deadlock with no nested synchronized blocks

HiddenDeadlockDemo.javaJava
import java.lang.management.ManagementFactory;import java.lang.management.ThreadInfo;import java.lang.management.ThreadMXBean;import java.util.Arrays;import java.util.Comparator;import java.util.concurrent.CountDownLatch;
class Customer {    private int wallet = 500;
    synchronized void payStore(Store store, int amount) {        wallet -= amount;        HiddenDeadlockDemo.pause();        store.receive(amount);    }
    synchronized void credit(int amount) { wallet += amount; }}
class Store {    private int till = 0;
    synchronized void receive(int amount) { till += amount; }
    synchronized void refund(Customer customer, int amount) {        till -= amount;        HiddenDeadlockDemo.pause();        customer.credit(amount);    }}
public class HiddenDeadlockDemo {    static final CountDownLatch bothInside = new CountDownLatch(2);   // demo only
    static void pause() {        bothInside.countDown();        try { bothInside.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }    }
    public static void main(String[] args) throws InterruptedException {        Customer meena = new Customer();        Store store = new Store();        Thread pay = new Thread(() -> meena.payStore(store, 60), "pay-order");        Thread refund = new Thread(() -> store.refund(meena, 20), "refund-return");        pay.setDaemon(true);        refund.setDaemon(true);        pay.start();        refund.start();        pay.join(500);        refund.join(500);
        ThreadMXBean mx = ManagementFactory.getThreadMXBean();        ThreadInfo[] infos = mx.getThreadInfo(mx.findDeadlockedThreads());        Arrays.sort(infos, Comparator.comparing(ThreadInfo::getThreadName));        for (ThreadInfo info : infos) {            System.out.println(info.getThreadName() + " holds a lock and waits for a "                    + info.getLockInfo().getClassName() + " held by " + info.getLockOwnerName());        }    }}
Output
pay-order holds a lock and waits for a Store held by refund-return
refund-return holds a lock and waits for a Customer held by pay-order

What this code does

  • No method has two nested synchronized blocks. payStore holds the Customer lock and calls store.receive; refund holds the Store lock and calls customer.credit. The latch only forces the bad timing.
  • Fix: in both methods, update your own field under your own lock and call the other object after the block ends (an open call), or move both operations into one transfer method that locks in a fixed order.

Each call takes a second lock while holding the first, and the two paths take them in opposite orders.

To find it, write down for every method which lock it holds and which other locks it can reach from there, including through calls. If lock A leads to lock B on one path and B leads to A on another, a deadlock is possible. Fix it with a fixed order, or by calling the other object only after releasing your own lock (an open call).

Find the broken invariant: check and act in separate steps

A broken invariant often hides behind methods that are each synchronized. hasSpace() and add() are both safe, but if (list.hasSpace()) list.add(name) is two separate locked steps, and another thread can take the last place in between.

Example 2 · Every method is synchronized, the rule still breaks

WaitlistOverflowDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;
class Waitlist {    // rule: never more than 'capacity' names    private final int capacity;    private final List<String> names = new ArrayList<>();
    Waitlist(int capacity) { this.capacity = capacity; }
    synchronized boolean hasSpace() { return names.size() < capacity; }    synchronized void add(String name) { names.add(name); }    synchronized int size() { return names.size(); }}
public class WaitlistOverflowDemo {    static final CyclicBarrier bothChecked = new CyclicBarrier(2);
    static void register(Waitlist list, String name) {        if (list.hasSpace()) {                 // check (locked)...            try {                bothChecked.await();            } catch (InterruptedException | BrokenBarrierException e) {                return;            }            list.add(name);                    // ...then act (locked again, separately)        }    }
    public static void main(String[] args) throws InterruptedException {        Waitlist hackathon = new Waitlist(30);        for (int i = 1; i <= 29; i++) hackathon.add("team-" + i);
        Thread a = new Thread(() -> register(hackathon, "team-ByteBusters"));        Thread b = new Thread(() -> register(hackathon, "team-NullPointers"));        a.start();        b.start();        a.join();        b.join();
        System.out.println("Capacity 30, registered " + hackathon.size()                + (hackathon.size() > 30 ? ": rule broken" : ": rule holds"));    }}
Output
Capacity 30, registered 31: rule broken

What this code does

  • Both teams saw one free place, because hasSpace() returned true for both before either add ran. The barrier only forces that timing; without it the bug appears rarely, during a registration rush.
  • The fix is one method, registerIfSpace, that checks and adds inside a single lock. Practice 3 asks you to write it.

Look for an if that reads shared state and then changes it through a different call, and for one rule whose fields are guarded by different locks. The fix is one method that checks and acts under one lock, such as registerIfSpace, or a single atomic method that does both, such as merge or compareAndSet.

Read a short thread dump: deadlock on ReentrantLock

With ReentrantLock, a dump looks a little different from the synchronized case. The stuck threads are WAITING (parking), and the lock they want appears as - parking to wait for <0x...> (a java.util.concurrent.locks.ReentrantLock$NonfairSync).

Example 3 · The same deadlock with ReentrantLock

SeatLockHang.javaJava
import java.util.concurrent.CountDownLatch;import java.util.concurrent.locks.ReentrantLock;
class Seat {    final String number;    final ReentrantLock lock = new ReentrantLock();    Seat(String number) { this.number = number; }}
public class SeatLockHang {    static final CountDownLatch bothHoldOne = new CountDownLatch(2);
    static void bookPair(Seat first, Seat second) {        first.lock.lock();        try {            bothHoldOne.countDown();            bothHoldOne.await();            second.lock.lock();            try {                System.out.println("never printed");            } finally {                second.lock.unlock();            }        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        } finally {            first.lock.unlock();        }    }
    public static void main(String[] args) throws InterruptedException {        Seat h7 = new Seat("H7"), h8 = new Seat("H8");        Thread a = new Thread(() -> bookPair(h7, h8), "booking-priya");        Thread b = new Thread(() -> bookPair(h8, h7), "booking-kabir");        a.setDaemon(true);        b.setDaemon(true);        a.start();        b.start();        System.out.println("PID: " + ProcessHandle.current().pid());        System.out.println("Stuck on purpose for 30 seconds: run jstack -l with this PID now.");        a.join(30_000);    }}
Sample output
PID: 27432
Stuck on purpose for 30 seconds: run jstack -l with this PID now.

What this code does

  • The opposite-order bug again, with ReentrantLock instead of synchronized. Line 14 takes the first seat's lock and line 18 waits for the second one.
  • It stays stuck for 30 seconds so that you can run jstack -l on it. The stuck threads are daemon threads, so the program still exits; your PID will differ.

Example 4 · jstack -l on the stuck seat booking

Terminal
jstack -l 27432
Sample output
...
"booking-priya" #21 [27256] daemon prio=5 os_prio=0 cpu=0.00ms elapsed=3.57s tid=0x0000021d658507c0 nid=27256 waiting on condition  [0x0000008328dfe000]
   java.lang.Thread.State: WAITING (parking)
        at jdk.internal.misc.Unsafe.park(java.base@21.0.7/Native Method)
        - parking to wait for  <0x0000000091a92e60> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
        at java.util.concurrent.locks.LockSupport.park(java.base@21.0.7/LockSupport.java:221)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.7/AbstractQueuedSynchronizer.java:754)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.7/AbstractQueuedSynchronizer.java:990)
        at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@21.0.7/ReentrantLock.java:153)
        at java.util.concurrent.locks.ReentrantLock.lock(java.base@21.0.7/ReentrantLock.java:322)
        at SeatLockHang.bookPair(SeatLockHang.java:18)
        at SeatLockHang.lambda$main$0(SeatLockHang.java:33)
        at SeatLockHang$$Lambda/0x0000021d01000c38.run(Unknown Source)
        at java.lang.Thread.runWith(java.base@21.0.7/Thread.java:1596)
        at java.lang.Thread.run(java.base@21.0.7/Thread.java:1583)

   Locked ownable synchronizers:
        - <0x0000000091a92de8> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

"booking-kabir" #22 [22188] daemon prio=5 os_prio=0 cpu=0.00ms elapsed=3.57s tid=0x0000021d65855250 nid=22188 waiting on condition  [0x0000008328efe000]
   java.lang.Thread.State: WAITING (parking)
        at jdk.internal.misc.Unsafe.park(java.base@21.0.7/Native Method)
        - parking to wait for  <0x0000000091a92de8> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
        at java.util.concurrent.locks.LockSupport.park(java.base@21.0.7/LockSupport.java:221)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.7/AbstractQueuedSynchronizer.java:754)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.7/AbstractQueuedSynchronizer.java:990)
        at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@21.0.7/ReentrantLock.java:153)
        at java.util.concurrent.locks.ReentrantLock.lock(java.base@21.0.7/ReentrantLock.java:322)
        at SeatLockHang.bookPair(SeatLockHang.java:18)
        at SeatLockHang.lambda$main$1(SeatLockHang.java:34)
        at SeatLockHang$$Lambda/0x0000021d01001000.run(Unknown Source)
        at java.lang.Thread.runWith(java.base@21.0.7/Thread.java:1596)
        at java.lang.Thread.run(java.base@21.0.7/Thread.java:1583)

   Locked ownable synchronizers:
        - <0x0000000091a92e60> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)

...
Found one Java-level deadlock:
=============================
"booking-priya":
  waiting for ownable synchronizer 0x0000000091a92e60, (a java.util.concurrent.locks.ReentrantLock$NonfairSync),
  which is held by "booking-kabir"

"booking-kabir":
  waiting for ownable synchronizer 0x0000000091a92de8, (a java.util.concurrent.locks.ReentrantLock$NonfairSync),
  which is held by "booking-priya"

...
Found 1 deadlock.

What this code does

  • Both booking threads are WAITING (parking) in ReentrantLock.lock, called from SeatLockHang.bookPair line 18. Under "Locked ownable synchronizers", booking-priya holds ...2de8 and parks on ...2e60, while booking-kabir holds ...2e60 and parks on ...2de8.
  • The report at the end confirms the cycle with "waiting for ownable synchronizer". Other threads were left out (...), and the addresses and ids change on every run.

With jstack -l, each thread block ends with Locked ownable synchronizers: the Lock objects that thread holds.

Match them as before: each thread parks on an address that the other thread lists as held. The JVM still finds this cycle and prints "Found one Java-level deadlock", with "waiting for ownable synchronizer" instead of "waiting to lock monitor".

Use jstack -l <pid> or jcmd <pid> Thread.print -l. Without -l, the dump does not list which ReentrantLocks each thread holds.

Mixed fix-the-bug: the usual suspects

These four patterns cover most of the bugs in this section. Check every piece of shared code against them.

Example 5 · Lost votes: get then put on ConcurrentHashMap

VoteLossDemo.javaJava
import java.util.concurrent.ConcurrentHashMap;
public class VoteLossDemo {    static int count(boolean useMerge) throws InterruptedException {        ConcurrentHashMap<String, Integer> votes = new ConcurrentHashMap<>();        Thread[] booths = new Thread[4];        for (int i = 0; i < booths.length; i++) {            booths[i] = new Thread(() -> {                for (int v = 0; v < 10_000; v++) {                    if (useMerge) {                        votes.merge("Asha", 1, Integer::sum);            // one atomic step                    } else {                        Integer old = votes.get("Asha");                 // step 1                        votes.put("Asha", old == null ? 1 : old + 1);    // step 2                    }                }            });            booths[i].start();        }        for (Thread t : booths) t.join();        return votes.get("Asha");    }
    public static void main(String[] args) throws InterruptedException {        System.out.println("get then put: " + count(false) + " votes (expected 40000)");        System.out.println("merge:        " + count(true) + " votes");    }}
Sample output
get then put: 23394 votes (expected 40000)
merge:        40000 votes

What this code does

  • Each call on ConcurrentHashMap is thread-safe, but get followed by put is two calls: two booths read the same count and both write count + 1. Thousands of votes vanish, a different number on every run.
  • merge reads, adds and writes in one atomic step for that key, so all 40,000 votes are counted.

The four patterns, with their usual fixes:

  • get then put on a concurrent map, or count++ on a shared field → merge, compute, computeIfAbsent, or an atomic class.
  • synchronized (new Object()), or one rule guarded by two different locks → one shared lock for the whole rule.
  • A stop flag that is not volatile → make it volatile (or an AtomicBoolean), or stop the thread with interrupt().
  • Locks taken in opposite orders, or listeners called under a lock → lock ordering and open calls.

Finish up

Mark complete & continue

Next: Parallel word counter