Skip to content

Finding a deadlock

Every few weeks, the desk’s transfer service stops answering. Nothing is logged, the CPU is idle, and a restart fixes it. By the time anyone takes a thread dump, it’s been restarted. Its tests pass. Nobody has made it hang on purpose, so nobody can say whether a change fixed it or the hangs just haven’t come back yet.

A bug that shows itself once in a few million calls won’t be found by running the calls again. This guide finds it by reading the code into a spec and letting a model checker try every order of events, then fixes it and pins the fix with the checks that can hold it. It’s the third guide on one trading desk, after “From design to code” and “From code to design”, with the same tools:

Step Tool
1. Write down what the code does, as a spec TLA+
2. Ask whether any order of events gets stuck TLC, TLA+‘s model checker
3. Fix the code, and check the fixed spec TLA+ and TLC
4. Pin the fix TLC in the build, and proptastic, the moves on two threads

The desk keeps a book for each office, London and New York, each with a position in one stock and a limit. A move shifts shares from one book to the other. Each book has a lock, and a move holds both while it works, so no one sees a book half moved:

Book.java
/** Runs {@code work} holding this book's lock, waiting for it if need be. */
public void whileLocked(Runnable work) {
lock.lock();
try {
work.run();
} finally {
lock.unlock();
}
}
/** Moves {@code quantity} to {@code other}, if it fits within its limit. */
public void giveTo(Book other, long quantity) {
if (other.position + quantity <= other.limit) {
position -= quantity;
other.position += quantity;
}
}
TransferDesk.java
/** Moves {@code quantity} from one book to the other, holding both. */
@Override
public void move(Book from, Book to, long quantity) {
from.whileLocked(() -> to.whileLocked(() -> from.giveTo(to, quantity)));
}

Its tests move shares one way, the other way, and past the limit:

TransferDeskTest.java
@Test
void aMoveTakesFromOneBookAndGivesToTheOther() {
var london = new Book("London", 80, 100);
var newYork = new Book("NewYork", 80, 100);
new TransferDesk().move(london, newYork, 15);
assertEquals(65, london.position());
assertEquals(95, newYork.position());
}
@Test
void aMoveThatWouldPassTheLimitDoesNothing() {
var london = new Book("London", 80, 100);
var newYork = new Book("NewYork", 90, 100);
new TransferDesk().move(london, newYork, 15);
assertEquals(80, london.position());
assertEquals(90, newYork.position());
}
@Test
void movesGoBothWays() {
var london = new Book("London", 80, 100);
var newYork = new Book("NewYork", 80, 100);
var desk = new TransferDesk();
desk.move(london, newYork, 15);
desk.move(newYork, london, 15);
assertEquals(80, london.position());
assertEquals(80, newYork.position());
}

They pass. The last one even moves both ways, but one move after the other, on one thread.

TLA+ describes a system as a state, the values of some variables, and the steps that change it. That description is a spec. TLC, TLA+‘s model checker, takes every step that can be taken, in every order, from the first state, and checks every state it reaches. One thing it checks without being asked is deadlock: a state from which no step can be taken at all.

The symbols this guide uses:

TLA+ Read it as
x' = x + 1 the value of x after the step is x + 1
/\ and \/ and, or; a column of them is a list
UNCHANGED x x stays the same in this step
[holder EXCEPT ![b] = w] holder, with b’s entry now w
[w1 |-> "London", w2 |-> "NewYork"] a function, or record: w1 maps to "London"
\E w \in Workers : … for some worker w, …
\A w \in Workers : … for every worker w, …

What is one step? A step is what happens without anything else happening in the middle. In “From code to design”, each synchronized method was one. Here a method isn’t: move takes one lock, then another, and another thread can run between the two. So a move is three steps: lock the first book, lock the second, and move the shares and let both locks go. A lock that’s held can’t be taken, so a step that needs it waits.

What is the state? Each book’s position, who holds each book’s lock, and how far each worker has got.

How big is the world? Two books and two workers, moving 15 in opposite directions: w1 from London to New York, w2 from New York to London. One worker can’t deadlock, and two moving the same way take the locks in the same order, so this is the smallest world where the question has an interesting answer.

Left out: the thread pool, the service around the desk, any other books, and the amounts, beyond one move of 15 each. A spec that translated every line would bury the two lock calls under everything else. Hillel Wayne found a model could “sometimes convert Python into a passable spec”, but “wasn’t good at recognizing abstraction” (Computer Things, 2025), and abstraction is most of the work here. Specula, which won the TLA+ Foundation’s 2025 GenAI challenge, drafts specs from system code and then checks them against the code’s runs; either way, a draft is a claim about the code to check.

In the code In the spec
a Book’s position position[b]
a Book’s ReentrantLock holder[b]: a worker, or "nobody"
from.whileLocked(…), the outer call the step LockFirst(w)
to.whileLocked(…), the inner call the step LockSecond(w)
from.giveTo(to, quantity), then both locks let go the step Move(w)
two threads, each calling move the workers w1 and w2, each with a status

The books and workers, and which lock each worker takes first. Ordered is off for now: the inherited desk locks from, then to. It’s there for the fix.

Books.tla
Books == {"London", "NewYork"}
Workers == {"w1", "w2"}
\* w1 moves London to New York; w2 moves New York to London.
From == [w1 |-> "London", w2 |-> "NewYork"]
To == [w1 |-> "NewYork", w2 |-> "London"]
\* The order the fix locks books in: by name, as the Java compares them.
Rank == [London |-> 1, NewYork |-> 2]
\* The book a worker locks first, and second.
First(w) == IF Ordered /\ Rank[To[w]] < Rank[From[w]] THEN To[w] ELSE From[w]
Second(w) == IF First(w) = From[w] THEN To[w] ELSE From[w]

The steps:

Books.tla
LockFirst(w) ==
/\ status[w] = "new"
/\ holder[First(w)] = "nobody"
/\ holder' = [holder EXCEPT ![First(w)] = w]
/\ status' = [status EXCEPT ![w] = "has one"]
/\ UNCHANGED position
LockSecond(w) ==
/\ status[w] = "has one"
/\ holder[Second(w)] = "nobody"
/\ holder' = [holder EXCEPT ![Second(w)] = w]
/\ status' = [status EXCEPT ![w] = "has both"]
/\ UNCHANGED position
Move(w) ==
/\ status[w] = "has both"
/\ IF position[To[w]] + Quantity <= Limit
THEN position' = [position EXCEPT ![From[w]] = @ - Quantity,
![To[w]] = @ + Quantity]
ELSE UNCHANGED position
/\ holder' = [b \in Books |-> IF holder[b] = w THEN "nobody" ELSE holder[b]]
/\ status' = [status EXCEPT ![w] = "done"]
\* Both moves are over: the desk is idle, which isn't a deadlock.
Finished ==
/\ \A w \in Workers : status[w] = "done"
/\ UNCHANGED vars
Next == (\E w \in Workers : LockFirst(w) \/ LockSecond(w) \/ Move(w))
\/ Finished

In words: a new worker takes its first book’s lock if nobody holds it. Holding one, it takes its second the same way. Holding both, it moves 15 if the other book has room (@ is the old value), lets both locks go, and is done. If a lock it needs is held, none of its steps can be taken: that’s waiting. Finished says that once both moves are over, the desk may sit idle; without it, TLC would call the end of the work a deadlock too.

The config sets the numbers and leaves Ordered off. TLC checks for deadlock by default, and a comment above these lines, \* check: deadlock, tells the build’s TLC task to leave that check on:

designs/books.cfg
CONSTANTS
Quantity = 15
Start = 80
Limit = 100
Ordered = FALSE
SPECIFICATION Spec
INVARIANT Within
Before reading on: can the two moves get stuck?

Yes. Each can take its first lock before the other takes its second.

TLC prints only the variables each step changes, then the last state in full:

Error: Deadlock reached.
Error: The behavior up to this point is:
State 1: <Initial predicate>
/\ holder = [London |-> "nobody", NewYork |-> "nobody"]
/\ position = [London |-> 80, NewYork |-> 80]
/\ status = [w1 |-> "new", w2 |-> "new"]
State 2: <LockFirst line 37, col 3 to line 41, col 23 of module Books>
/\ holder = [London |-> "w1", NewYork |-> "nobody"]
/\ status = [w1 |-> "has one", w2 |-> "new"]
State 3: <LockFirst line 37, col 3 to line 41, col 23 of module Books>
/\ holder = [London |-> "w1", NewYork |-> "w2"]
/\ position = [London |-> 80, NewYork |-> 80]
/\ status = [w1 |-> "has one", w2 |-> "has one"]
8 states generated, 7 distinct states found, 2 states left on queue.

Two steps, and no step after them can be taken. In the code’s terms:

  1. Thread w1 calls move(london, newYork, 15). The outer whileLocked takes London’s lock.
  2. Thread w2 calls move(newYork, london, 15). Its outer whileLocked takes New York’s lock.
  3. w1’s inner whileLocked asks for New York’s lock, which w2 holds, and waits.
  4. w2’s inner whileLocked asks for London’s lock, which w1 holds, and waits.

Neither lock is ever let go, because each is let go only after the other is taken. That’s the hang: idle CPU, nothing logged, two threads parked for ever. It needs two moves in opposite directions to arrive within the moment between one move’s two lock calls, which is why it happens every few weeks and never in a test.

The textbook fix is one lock order: whichever way a move goes, take the locks in the same order, here by the books’ names. Then the second worker to arrive waits for its first lock, holding nothing, and the first finishes. The spec says it first, with Ordered on:

Model checking completed. No error has been found.
14 states generated, 12 distinct states found, 0 states left on queue.

No order of events gets stuck, and no book passes its limit. The code, changed to match:

OrderedTransferDesk.java
/**
* Moves {@code quantity} from one book to the other, holding both, and
* always locking the book whose name comes first first.
*/
@Override
public void move(Book from, Book to, long quantity) {
var inOrder = from.name().compareTo(to.name()) < 0;
var first = inOrder ? from : to;
var second = inOrder ? to : from;
first.whileLocked(() -> second.whileLocked(() -> from.giveTo(to, quantity)));
}

compareTo is the spec’s Rank: London before New York. The docs keep both desks, so both can be run; in your code, the fix replaces the old move.

A hang that came every few weeks can’t be shown gone by waiting a few weeks. Two things hold this fix: TLC on the spec, on every build, and proptastic running the real desk’s moves on two threads, trying the ways their locks can interleave.

The fixed spec is checked on every build: ./gradlew check runs TLC on designs/books-ordered.cfg and fails unless what it finds is the verdict above. A change to the spec that lets the moves get stuck again fails the build with TLC’s trace. TLC checks the spec, though, not the Java: what ties them is the mapping above, and the next test.

In the other guides, a stateful test took the desk’s steps one at a time, on one thread. A step is a whole call, so taken one at a time, move never stops between its two lock calls, which is the only place this bug lives. Steps on threads can stop there. The test needs three things.

The steps, as an interface. What the desk’s callers do to the books is one thing, a move. Marked @StepBuilder, the interface is the test’s list of steps, and proptastic’s annotation processor writes two classes from it as the test code compiles (Steps from an interface sets it up): BookingSteps, the steps, with a typed method for each, and BookingStep, one step, for a pin.

Booking.java
/** What the desk's callers do to the books: one step, a move. */
@StepBuilder
interface Booking {
void move(String from, String to, long quantity);
}

Books on locks proptastic schedules. Books is the state the threads share: London and New York at 80 of 100, the desk under test, and the interface’s one step. Each book is opened with lock("London") or lock("NewYork") through the Book constructor that takes a lock, the one seam the test needs. lock(name) is a ReentrantLock: where proptastic runs steps on threads, taking it is a point where proptastic may stop one thread and run the other, and a thread that asks for a lock the other holds waits for it.

Books.java
/** Moves {@code quantity} between the books named, on the desk. */
@Override
public void move(String from, String to, long quantity) {
desk.move(named(from), named(to), quantity);
}
/** Whether both books are within their limits: the spec's Within. */
boolean withinLimits() {
return fits(london) && fits(newYork);
}
private static boolean fits(Book book) {
return book.position() <= book.limit();
}

The desk’s own code doesn’t know it’s being tested: move names the books and calls it.

The steps, drawn. moves gives the steps on whichever desk it’s handed, so the inherited desk and the fix are tested alike. BookingSteps.steps(…) starts each try on new books, .move(…) is the interface’s step with a domain for each of its arguments, and the invariant is the spec’s Within:

MovesAtOnceTest.java
/** Moves between the two books, on whichever desk is given. */
static BookingSteps<Books> moves(Transfers desk) {
return BookingSteps.steps(() -> new Books(desk))
.move(books(), books(), quantities())
.invariant("no book passes its limit", Books::withinLimits);
}
static Domain<String> books() {
return elements("London", "NewYork");
}
static Domain<Long> quantities() {
return longs().atLeast(1).atMost(20);
}

.threads(2) runs each try’s moves on two threads sharing one Books:

MovesAtOnceTest.java
@Test
@Tag("failing")
void theInheritedDeskNeverDeadlocks() {
forAll(moves(new TransferDesk())).threads(2).check();
}

Each try draws a few moves for each thread, and some to take first, before the threads start, and runs them on every schedule with up to two preemptions: every way of stopping one thread and running the other, at up to two of the points it can. On the inherited desk it fails, the same way every run:

Terminal window
deadlock: thread 1 holds "London", waits for "NewYork"; thread 2 holds "NewYork", waits for "London"
theInheritedDeskNeverDeadlocks failed after 1 try (seed 0x2)
shrunk steps:
thread 1 thread 2
1. move("London", "NewYork", 1)
locks "London"
paused before it takes "NewYork"
1. move("NewYork", "London", 1)
locks "NewYork"
waits for "London"
waits for "NewYork"
pin it:
.example(
thread(move("London", "NewYork", 1L)),
thread(move("NewYork", "London", 1L)))
// import static deadlock.BookingStep.*
rerun:
PROPTASTIC_SEED=0x2 ./gradlew test --tests 'MovesAtOnceTest.theInheritedDeskNeverDeadlocks'
  • The first line says what went wrong: a deadlock, named lock by lock. Thread 1 holds London and waits for New York; thread 2 holds New York and waits for London. That’s TLC’s last state, in Java.
  • shrunk steps: is the interleaving, a column for each thread, time going down. Shrinking took the moves down to one each way, of 1 share. Thread 1, moving London to New York, locks London. Then thread 2, moving the other way, locks New York and asks for London, which thread 1 holds. Then thread 1 asks for New York. It’s the order TLC’s trace drew, thread 1 as w1: each takes its first lock before either takes its second.
  • pin it: is each thread’s moves, a thread(…) for each, written with BookingStep, the class generated from Booking. Paste it on a test and it replays those moves, on every schedule.

It took one try, not a few weeks, and it fails the same way on every run: the schedules come in a fixed order, and the moves come from the seed.

The same moves, on the fixed desk:

MovesAtOnceTest.java
@Test
void theFixNeverDeadlocks() {
forAll(moves(new OrderedTransferDesk())).threads(2).check();
}

It passes, and says what it searched:

Terminal window
passed on 2 threads, 100 runs (every schedule with up to 2 preemptions: 5,724) · no deadlock · held "no book passes its limit" · each fits an order of its steps, one at a time
how sure: 0 of 100 runs failed, so under 3% of runs drawn this way fail it (95% confidence)
why: https://docs.proptastic.io/concepts/how-sure-is-a-pass/

The first line is exact. Each of the 100 runs drew a few moves for each thread, and proptastic ran them on every schedule with up to two preemptions, 5,724 schedules in all. On each, both threads finished, so no deadlock; no book passed its limit; and some order of the moves, one at a time on new books, left them where the threads left them, as Books’s toString says, so a move lost between the threads would show too. The schedules come in a fixed order, not at random, so the line doesn’t estimate over them: a schedule within the bound was run. The second line is over the runs, whose moves are drawn: with no failure in 100, fewer than 3% of runs drawn this way would fail. Neither says the desk can’t deadlock with more preemptions or more threads: what this shows, below, says where the edges are.

The trace TLC found is pinned beside it, so the fix is held to it by name, whatever the seed draws. It’s written as the failure’s pin was, move(…) from BookingStep in a thread(…) for each thread, with TLC’s moves: w1 London to New York, w2 back, 15 each:

MovesAtOnceTest.java
@Test
void theTraceTlcFoundStaysFixed() {
forAll(moves(new OrderedTransferDesk()))
.threads(2)
.example(
thread(move("London", "NewYork", 15L)), // the trace TLC found
thread(move("NewYork", "London", 15L)))
.check();
}

A pin holds each thread’s moves, not a schedule: every schedule is tried for it too. And it’s code the compiler checks: rename move in Booking, or give it another argument, and the pin stops compiling, where a step("move", …) written by hand would fail only when it ran.

TLC checks every order of events, for the spec; the test checks the real desk’s lock calls, for the moves it draws and the one TLC found. Together they cover what each misses alone.

In proptastic’s repository:

Terminal window
# TLC on each config, Books among them, into build/tlc-designs
./gradlew tlcDesigns
# the desk's tests, and the moves on two threads
./gradlew docsTest --tests 'deadlock.*'

TLC found every way two opposite moves can interleave at the level of lock calls, and one of them never ends. With one lock order, none gets stuck, for two books and two workers. The test on two threads tried every interleaving of the real desk’s lock calls, up to two preemptions, for the moves it drew and the one TLC found: the inherited desk deadlocks, and the fix doesn’t.

It doesn’t show the desk can’t deadlock elsewhere. The spec has two books, two workers and one move each; a third lock somewhere else, or a lock held across a call to another service, is outside it. The test sees only the locks proptastic made: a synchronized block or a lock the desk made for itself isn’t a point it can stop at. The spec was read out of the code, not checked against it step by step, so a difference between them is found only where the test reaches.

Privacy