Skip to content

Concurrency

A class that several threads share can be right one call at a time and wrong when two calls overlap. Its tests call it one call at a time, so they pass. A test that starts two threads overlaps the calls only when the timing happens to: it passes for weeks, fails once in CI, and never fails again for anyone who looks. This guide runs a stateful test’s steps on two threads at once instead. proptastic decides where the threads interleave, tries every interleaving that matters, and when one breaks the class, shows the fewest steps and that interleaving, the same on every run.

It needs the stateful guide’s steps; it builds on them with three things: a lock proptastic can schedule, a way for a step to say what it saw, and .threads(2).

An account is shared by the threads that pay out of it. Every read and write of its balance holds its lock, and a withdrawal checks the balance covers it before taking it:

@Override
public boolean withdraw(long amount) {
if (!covers(amount)) {
return false;
}
take(amount);
return true;
}
private boolean covers(long amount) {
lock.lock();
try {
return balance >= amount;
} finally {
lock.unlock();
}
}
private void take(long amount) {
lock.lock();
try {
balance -= amount;
} finally {
lock.unlock();
}
}

Its tests pass:

@Test
void aWithdrawalTheBalanceCoversIsTaken() {
var account = new SharedAccount(100);
assertTrue(account.withdraw(60));
assertEquals(40, account.balance());
}
@Test
void aWithdrawalPastTheBalanceIsRefused() {
var account = new SharedAccount(100);
assertTrue(account.withdraw(60));
assertFalse(account.withdraw(60));
assertEquals(40, account.balance());
}

The second even makes two withdrawals that can’t both be covered, but one after the other, on one thread.

A lock proptastic schedules. lock("account") is a ReentrantLock. Where proptastic runs steps on threads, taking it is a point where proptastic may stop one thread and run another, and a thread that asks for it while another holds it waits for it. Anywhere else, it’s a plain lock. The account takes its lock in a constructor the test can call: that constructor is the one seam the test needs.

What a step saw. On one thread, a step checks itself with assertions. On two, what a withdrawal should return depends on what the other thread did, so the step records what it saw instead, with record(…). proptastic then asks whether some order of the steps, taken one at a time, would have given everything the threads saw. If none does, the threads saw something no one-at-a-time use of the account can produce. That’s linearizability, the usual meaning of “safe to share”.

Steps on threads. forAll(steps).threads(2) runs each try’s steps on two threads sharing one account.

The steps are the stateful guide’s kind. The account is opened on a scheduled lock, through a function, so the fix can be tested with the same steps later; a withdrawal records its result:

/** Steps on an account that {@code open} makes, guarded by {@code lock}. */
static Steps<Account> anAccount(Function<ReentrantLock, Account> open) {
return steps(() -> open.apply(lock("account")))
.step("deposit", amounts(), Account::deposit)
.step("withdraw", amounts(), SharedAccountTest::withdraw);
}
/** A withdrawal, recording whether the account paid it. */
static void withdraw(Account account, long amount) {
record(account.withdraw(amount));
}

amounts() is longs().atLeast(1).atMost(100), and every account opens with 100 in it.

@Test
@Tag("failing")
void withdrawalsAtOnceKeepTheBooks() {
forAll(anAccount(lock -> new SharedAccount(100, lock))).threads(2).check();
}

Each try draws some steps to take first, on one thread, then a list of steps for each thread, two steps each on average. It fails:

Terminal window
no order of the threads' steps, one at a time, gives what they saw
they saw: thread 1: withdraw(1) → true
thread 2: withdraw(100) → true
one at a time: withdraw(100) → true, then withdraw(1) → false
withdraw(1) → true, then withdraw(100) → false
thread 1's withdraw(1) → true began before thread 2's withdraw(100)
and ended after it
withdrawalsAtOnceKeepTheBooks failed after 1 try (seed 0x90)
shrunk steps:
thread 1 thread 2
1. withdraw(1)
locks and unlocks "account"
paused before it takes "account"
1. withdraw(100)
locks and unlocks "account"
locks and unlocks
→ true
locks and unlocks
→ true
pin it:
.example(thread(step("withdraw", 1L)), thread(step("withdraw", 100L)))
// typed pins come from @StepBuilder
rerun:
PROPTASTIC_SEED=0x90 ./gradlew test --tests 'SharedAccountTest.withdrawalsAtOnceKeepTheBooks'
  • The first line says what went wrong: no order of the steps, one at a time, gives what the threads saw.
  • they saw: is each thread’s steps as they ended on it: both withdrawals were paid.
  • one at a time: is every order proptastic tried, and where each stopped fitting. Withdraw 100 first and the account is empty, so the 1 is refused; withdraw 1 first and 99 is left, so the 100 is refused. Neither order pays both. With more threads or steps there are more orders: it shows the four that got furthest and says how many more it tried.
  • The last line says which steps overlapped: thread 1’s withdrawal began before thread 2’s and ended after it, so either could have gone first, and something inside them let both through.
  • shrunk steps: is the interleaving, a column for each thread, time going down. Thread 1 checked the balance (locks and unlocks "account": it took the lock and let it go, with nothing in between), then thread 2 checked and took 100, while thread 1 waited between its check and its take. Then thread 1 took its 1, from an account that no longer had it. Where there’s one lock, a column names it the first time and not after. Each → is what a step recorded, written where it returned.
  • pin it: is each thread’s steps, a thread(…) for each, after a first(…) when any steps went before the threads.

The bug is the gap between covers and take. Each holds the lock, but nothing holds it from one to the other, so another withdrawal can take the money in between.

Shrinking left two withdrawals that come to more than 100: drop either and the other fits. Any two such withdrawals show the same bug, and the pin is the place to say so.

A race often needs the state set up first: an account paid into, an order placed, a session opened. Each try takes some steps on one thread first, before the threads start, then the threads’ steps at once. Open the account empty, and the withdrawals need a deposit before them:

@Test
@Tag("failing")
void withdrawalsFromAnEmptyAccountKeepTheBooks() {
forAll(anAccount(lock -> new SharedAccount(0, lock))).threads(2).check();
}
Terminal window
no order of the threads' steps, one at a time, gives what they saw
they saw: thread 1: withdraw(1) → true
thread 2: withdraw(1) → true
one at a time: withdraw(1) → true, then withdraw(1) → false
thread 1's withdraw(1) → true began before thread 2's withdraw(1)
and ended after it
withdrawalsFromAnEmptyAccountKeepTheBooks failed after 2 tries (seed 0x1)
shrunk steps:
first
1. deposit(1)
thread 1 thread 2
1. withdraw(1)
locks and unlocks "account"
paused before it takes "account"
1. withdraw(1)
locks and unlocks "account"
locks and unlocks
→ true
locks and unlocks
→ true
pin it:
.example(
first(step("deposit", 1L)),
thread(step("withdraw", 1L)),
thread(step("withdraw", 1L)))
// typed pins come from @StepBuilder
rerun:
PROPTASTIC_SEED=0x1 ./gradlew test --tests 'SharedAccountTest.withdrawalsFromAnEmptyAccountKeepTheBooks'

The deposit is under first, numbered, above the threads’ columns. A step’s place, first or on a thread, is drawn with it, so shrinking moves a step that needn’t overlap the others from its thread to before the threads, as it would make any choice simpler. What’s left on the threads is what must overlap for the bug to show, and everything above them only sets the state up. The pin starts with first(…), then a thread(…) for each thread.

The first steps can keep values the threads’ steps use, such as accounts they open, and a step’s argument from the state sees the state the first steps left. A value a step on a thread keeps isn’t drawn by another thread’s steps.

proptastic doesn’t start two threads and hope they collide. It runs one thread at a time, and switches threads only at points it can see: before each step, and before each lock(…) is taken. At every point it can let the running thread go on, or stop it and run another. Stopping a thread that could have gone on is a preemption.

For every try, proptastic runs the steps on every schedule with no preemptions, then every schedule with one, then every schedule with two: up to a thousand schedules a try. A thread that asks for a lock another holds waits, and another runs; that isn’t a preemption. Most concurrency bugs need two preemptions or fewer, so the bad interleaving comes up whenever the steps that need it are drawn, and the first one found has the fewest switches. Here it needed one: stop thread 1 between its check and its take.

Each schedule is checked three ways:

  • every thread finished, so no deadlock;
  • every invariant holds on the state the threads left;
  • some order of the steps, one at a time on a new account, gives everything the threads saw. The order must keep real time: a step that returned before another started stays first. And when the state has a toString, that order must leave the state saying what the threads left it saying, so a lost update is found even in steps that record nothing.

Only one thread runs at a time, the schedules come in a fixed order, and the steps come from the seed. So the same seed gives the same report, byte for byte: the rerun: line reproduces it, and mutastic judges a property on threads as it judges any other, the same way on every run of a mutant.

The pin replays each thread’s steps. It holds no schedule: a pinned example runs every schedule too, so it keeps finding the interleaving after the code changes how it locks. The pin can be made plainer by hand, to the two withdrawals the bug needs:

@Test
@Tag("failing")
void withdrawalsAtOnceKeepTheBooksPinned() {
forAll(anAccount(lock -> new SharedAccount(100, lock)))
.threads(2)
.example(thread(step("withdraw", 60L)), thread(step("withdraw", 60L)))
.tries(0)
.check();
}

It fails as the shrunk run did, the header saying failed on example 1 of 1: both withdrawals of 60 record true.

Hold the lock from the check to the take:

@Override
public boolean withdraw(long amount) {
lock.lock();
try {
if (balance < amount) {
return false;
}
balance -= amount;
return true;
} finally {
lock.unlock();
}
}

The same steps pass on the fix, with the pin kept as an example:

@Test
void theFixKeepsTheBooks() {
forAll(anAccount(lock -> new HeldAccount(100, lock)))
.threads(2)
.example(thread(step("withdraw", 60L)), thread(step("withdraw", 60L)))
.check();
}

A pass says what it searched:

Terminal window
passed on 2 threads, 101 runs (every schedule with up to 2 preemptions: 3,906) · no deadlock · 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 101 runs, the pinned one and 100 drawn, ran every schedule with up to two preemptions, 3,906 in all, and each schedule finished with every withdrawal fitting some order of them one at a time. The schedules come in a fixed order, not at random, so there’s no estimate over them: a schedule within the bound was run, or the line doesn’t say it was. A run with more than 1,000 schedules within the bound stops there, and the line then claims only the bounds it searched in full: up to 1 on 3 runs. The second line is over the runs, whose steps are drawn: with no failure in 100, fewer than 3% of runs drawn this way would fail.

proptastic switches threads only at the points it sees, so it finds a bug that needs another thread to run between two points. Between two lock(…) calls, as here, or between two steps, it does. Between two lines that nothing separates, it doesn’t:

  • A lock proptastic didn’t make (synchronized, a ReentrantLock of the class’s own, an atomic, a concurrent collection) isn’t a point. Give the class its lock through a constructor, as this account does, to make it one.
  • A thread that waits on something proptastic doesn’t schedule, such as a monitor another thread holds, a sleep, or a future from another thread, never comes back to a point. After ten seconds the run fails, saying which thread and where it was.
  • A condition (lock(…).newCondition()) is refused, saying so: a thread waiting on one would hang the schedule.
  • Steps that start threads of their own or depend on the time run differently on the same schedule, and the run fails saying so.

It also checks only that sharing the account changes nothing. The steps taken one at a time are the model, so a withdrawal that’s wrong on one thread, such as one that always pays, is wrong the same way one at a time, and this test passes on it. Keep the one-thread tests, or a stateful test with a model, for what the account should do; an invariant, such as “never overdrawn”, checks both. mutastic shows the split: on the fixed account, it finds that this test catches a removed unlock(), as a deadlock, every run, and that it misses a withdrawal that always pays, which only the one-thread tests can catch.

A deadlock is found and named, lock by lock, as two threads that each hold one lock and wait for the other’s: Finding a deadlock finds one in a real desk’s moves. For races that only bytecode-level scheduling can reach, between plain reads and writes, proptastic’s agent makes the code’s own reads, writes and locks into points: Races in plain code.

Every schedule proptastic runs takes one thread’s step at a time, each thread in its program order. That finds bugs in the order of steps: a lost update, a check and an act another thread gets between, a deadlock, a result no order of the steps one at a time could give. It can’t find bugs in what the memory model lets a CPU or the JIT do: a write another thread sees late or not at all, or two writes it sees in the other order.

Double-checked locking without volatile is the classic one:

private Config config; // not volatile
Config config() {
if (config == null) {
synchronized (this) {
if (config == null) config = new Config(load());
}
}
return config;
}

In every interleaving of these lines, a thread that sees config sees it built, so proptastic passes it. On real hardware another thread can see the reference before the fields the constructor wrote, a half-built Config. jcstress, OpenJDK’s concurrency stress harness, finds that: it runs a few fixed actions on real threads millions of times, across JVMs, and counts each outcome it sees, so it shows what the hardware and the JIT really do, and an ARM machine shows more than an x86 one.

The two answer different questions, and a concurrent class can need both:

  • proptastic: do these steps, in any order on any number of threads, give a result the steps one at a time could give? Generated steps, a search of the interleavings, the fewest steps and the interleaving that fails, and a seed that replays it.
  • jcstress: is this publication, fence or lock-free read safe under the memory model? A scenario you write and the outcomes you allow, run until the hardware shows its hand. It doesn’t generate steps, shrink, or replay a failure on demand.

Privacy