TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท java ยท concurrency

Threads, locks and race conditions

Threads run at the same time and share memory, so unprotected read-modify-write sequences can lose updates. Locks make critical sections run one thread at a time; careless locking can deadlock.

11 min3 animations

๐Ÿ–จ๏ธ Cheat sheet

One whiteboard, two writers

A whiteboard keeps a tally. Ana and Ben both need to add one. Each glances at the board (5), works out 6 in their head, and writes 6. Two people added one, but the tally only went up by one.

It doesn't happen every time, only when they happen to look at the same moment, which makes it maddening to find.

Race conditions

Threads share the heap. count++ looks like one operation but is three: read, add, write. When two threads interleave those steps, one update is lost. That is a race condition: the result depends on timing.

Races hide in tests and appear under load. Any check-then-act (if (!map.containsKey(k)) map.put(k, v)) or read-modify-write on shared mutable state is a candidate.

Two writers, one whiteboard3 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ“‹ Whiteboard tally
Press play and watch it happen!

One marker pen

The fix: there's one marker pen, and only whoever holds it may touch the tally. Anyone else waits for the pen. Each person's read-and-write now happens as one uninterrupted turn.

Locks

A lock makes a critical section mutually exclusive. In Java every object has a monitor:

1private int count;2 3public synchronized void increment() {   // one thread at a time4    count++;5}

ReentrantLock offers the same with extras (tryLock, timeouts, fairness). For a simple counter, AtomicInteger or LongAdder is faster, using lock-free compare-and-set. Better still, avoid shared mutable state: immutable objects and ConcurrentHashMap.merge remove whole classes of bugs.

One marker pen4 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ–Š๏ธ The one marker๐Ÿ“‹ Whiteboard tally
Press play and watch it happen!

Stuck forever

Some jobs need two pens. If Ana grabs red and Ben grabs blue, each waits for the other's, forever. The cure is a house rule: everyone picks up red before blue.

Deadlock

A deadlock happens when threads wait in a cycle for locks the others hold. Avoid it by acquiring locks in one global order, holding locks briefly, never calling unknown code while holding a lock, or using tryLock with a timeout. A thread dump (jstack <pid>) reports Java-level deadlocks directly.

Each holding what the other needs3 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ–๏ธ Red marker๐Ÿ–Š๏ธ Blue marker
Press play and watch it happen!

๐Ÿ”Ž Spot it in real code

This is the whiteboard and its marker pen as real Java code. Pick a label, then tap the line where that happens. Can you find all four?

Tap the line where you see: The tally everyone writes on.

0 of 4 placed

๐Ÿงฉ Finish the code

Now write the money-moving rules yourself. Each account has its own marker pen. Moving money needs both pens, and everyone must pick up the pen of the lower-numbered account first so nobody gets stuck. Every pen taken must be put back, even if something goes wrong, and a counter on the wall must never miss a transfer when many people count at once. Pick the code for each numbered gap.
  1. 1 The other account's pen, whichever way round the two came in
  2. 2 Add one to the wall counter so no count is ever lost
  3. 3 The part that always runs, even after a mistake
  4. 4 Put back the pen picked up first
1public class Bank {2    private final AtomicInteger transfers = new AtomicInteger();3 4    public void transfer(Account from, Account to, int amount) {5        Account first = from.id < to.id ? from : to;6        Account second = 1;7        first.lock.lock();8        try {9            second.lock.lock();10            try {11                from.balance -= amount;12                to.balance += amount;13                2;14            } 3 {15                second.lock.unlock();16            }17        } finally {18            4;19        }20    }21}
0 of 4 gaps filled

๐Ÿงช Debug it for real

  • ๐Ÿ›’The flash sale sold 112 units of an item with 100 in stockThe shop keeps its stock count on a whiteboard. During the sale, shoppers read the count, decided there was enough, and wrote down a smaller number. More games were sold than the shop had. Find out why and fix it.Java 21JUnit 5beginner25 min

๐Ÿงฉ Quick quiz

Quick quiz! 3 questions about Threads, locks and race conditions, told the same way as the story.
  1. Ana and Ben both read 5 and both write 6. What went wrong?
  2. What does the single marker pen guarantee?
  3. Ana holds red and wants blue; Ben holds blue and wants red. What's the cure?
Answer every question to check.Passing marks Threads, locks and race conditions as done.
Got the hang of Threads, locks and race conditions? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โ˜• Java concurrencyStep 1 of 5

Next on the path โ†’๐Ÿ—’๏ธ The Java memory model and volatile

๐Ÿ‘‰ Read next

  • ๐Ÿ“ŸCompletableFuture and asyncOrdering at a cafรฉ and getting a buzzer: order everything at once, sit down, and collect when it buzzes.
  • ๐Ÿ—’๏ธThe Java memory model and volatileWorkers copy the main board onto private notepads; marking an item "main board only" keeps everyone up to date.
  • ๐Ÿ”‘Distributed locks with RedisOne key to a shared meeting room, tagged with the borrower's name and a time it must come back by.
  • ๐ŸคตVirtual threadsA few waiters serving hundreds of tables, pinning each order to the pass instead of waiting beside one table.