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.
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
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:
1privateintcount;23publicsynchronizedvoidincrement() { // one thread at a time4count++;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
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
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 The other account's pen, whichever way round the two came in
2 Add one to the wall counter so no count is ever lost