Skip to content

Checks: concurrency and ownership

Templates for the four concurrency and ownership stories. Each one uses a pause point: a named place in production code where a test can stop a thread or process until it’s released. With pause points, a race that happens one run in a thousand happens on every run, so the wrong design fails every time.

A pause point can be as small as this, compiled out or disabled outside tests:

public final class PausePoints {
private static final Map<String, CountDownLatch> reached = new ConcurrentHashMap<>();
private static final Map<String, CountDownLatch> released = new ConcurrentHashMap<>();
private static volatile boolean enabled = false; // tests switch this on
public static void here(String name) throws InterruptedException {
if (!enabled || !released.containsKey(name)) return;
reached.get(name).countDown();
released.get(name).await();
}
public static void arm(String name) {
enabled = true;
reached.put(name, new CountDownLatch(1));
released.put(name, new CountDownLatch(1));
}
public static void awaitReached(String name) throws InterruptedException { reached.get(name).await(); }
public static void release(String name) { released.get(name).countDown(); }
}
  • Proves: two concurrent requests that each take a clinician off call leave at least one on call, and the second caller gets a clear refusal.
  • Fails for: snapshot isolation without a lock or serializable transactions. Two valid transactions left nobody on call.
  • Harness needs: a pause point between the check and the update.
@Test
void twoConcurrentRequestsLeaveSomeoneOnCall() throws Exception {
PausePoints.arm("after-on-call-count");
var rao = executor.submit(() -> onCall.takeOff("night-11-21", "rao"));
PausePoints.awaitReached("after-on-call-count"); // Rao has counted 2
var kim = executor.submit(() -> onCall.takeOff("night-11-21", "kim"));
Thread.sleep(200); // let Kim reach the same point
PausePoints.release("after-on-call-count");
var results = List.of(rao.get(), kim.get());
assertThat(db.onCallCount("night-11-21")).isGreaterThanOrEqualTo(1);
assertThat(results).extracting(Result::outcome).containsExactlyInAnyOrder(OFF_CALL, REFUSED_LAST_ON_CALL);
}

With PostgreSQL SERIALIZABLE, one transaction fails with SQLSTATE 40001 and the application retries it. The test above is unchanged: it checks the outcome the caller sees, so it also proves the retry is in place.

  • Proves: a worker whose lease expired while it was paused can’t overwrite the new owner’s result, and it learns that it lost ownership.
  • Fails for: a lease checked only by the worker. The worker that kept writing after its lease expired.
  • Harness needs: a pause point between the lease check and the write; a lock service with a controllable clock.
@Test
void aWriteFromAnExpiredLeaseIsRejectedAtTheDestination() throws Exception {
PausePoints.arm("before-report-write");
var a = executor.submit(() -> workerA.runNightlyReport());
PausePoints.awaitReached("before-report-write"); // A checked its lease (token 33)
lockClock.advance(Duration.ofSeconds(40)); // lease expires
workerB.runNightlyReport(); // B gets token 34 and writes
PausePoints.release("before-report-write");
var outcomeA = a.get();
assertThat(storage.read("reports/2026-11-21.json").writtenBy()).isEqualTo("B");
assertThat(outcomeA).isEqualTo(LOST_OWNERSHIP);
}

C-19: a delayed fill can’t republish an old value

Section titled “C-19: a delayed fill can’t republish an old value”
  • Proves: a cache fill that read the old value before a write, and finishes after the invalidation, is rejected; the next reader gets the new value.
  • Fails for: delete-on-write cache-aside. The cache that went stale right after invalidation.
  • Harness needs: a pause point between the database read and the cache write.
@Test
void aDelayedFillCannotRepublishTheOldPrice() throws Exception {
db.setPrice("P-7", "40.00"); // version 1
PausePoints.arm("before-cache-fill");
var reader = executor.submit(() -> catalog.price("P-7"));
PausePoints.awaitReached("before-cache-fill"); // reader holds version 1
catalog.updatePrice("P-7", "32.00"); // commit version 2, then invalidate
PausePoints.release("before-cache-fill");
reader.get();
assertThat(cache.get("P-7")).satisfiesAnyOf(
v -> assertThat(v).isEmpty(),
v -> assertThat(v).hasValueSatisfying(e -> assertThat(e.version()).isEqualTo(2)));
assertThat(catalog.price("P-7")).isEqualByComparingTo("32.00");
}

C-20: a compensation undoes only its own work

Section titled “C-20: a compensation undoes only its own work”
  • Proves: compensating a failed saga releases only its own reservation, leaves a concurrent saga’s reservation intact, and is safe to run twice.
  • Fails for: restoring a remembered total. The compensation that undid somebody else’s work.
  • Harness needs: run saga steps individually.
@Test
void compensationReleasesOnlyItsOwnReservationEvenTwice() {
inventory.setStock("P-3", 10);
var w1 = inventory.reserve("W1", "P-3", 2);
var w2 = inventory.reserve("W2", "P-3", 3);
sagas.compensate("W1");
sagas.compensate("W1"); // a retried compensation
assertThat(inventory.reservation(w2).status()).isEqualTo(HELD);
assertThat(inventory.reservation(w1).status()).isEqualTo(RELEASED);
assertThat(inventory.available("P-3")).isEqualTo(7);
}

Written and edited by Abhinav Taduka, enterprise software architect.