Video in progress

Strong Middle 🧪 Testing

In a class that has to be thread-safe, how do you try to catch a race condition with a test?

I use CountDownLatch or CyclicBarrier to start many threads at the same moment, run one operation thousands of times in parallel, and check the final invariant. But such a test doesn't prove there's no bug, it only raises the odds of finding it; for serious cases you need jcstress.

📖 Answer

A simple example, a balance counter:

@RepeatedTest(20)
void parallel_depozitlar_yoqolmaydi() throws Exception {
    var account = new Account();
    int threads = 16, perThread = 1_000;
    var start = new CountDownLatch(1);

    try (var pool = Executors.newFixedThreadPool(threads)) {
        List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < threads; i++) {
            futures.add(pool.submit(() -> {
                start.await();                       // everyone starts at the same time
                for (int j = 0; j < perThread; j++) account.deposit(1);
                return null;
            }));
        }
        start.countDown();
        for (var f : futures) f.get(10, TimeUnit.SECONDS);   // exceptions from inside show up too
    }

    assertEquals(threads * perThread, account.balance());
}

Important details:

  • without the latch, the first thread finishes before the second one starts, and there's no contention at all;
  • collect exceptions with Future.get, otherwise an error in another thread vanishes silently;
  • on a CI agent with few cores, the race shows up less often, so a passing test guarantees nothing.

Tests like this almost never catch memory visibility and reordering bugs. For those there's OpenJDK's jcstress tool: it runs the same small scenario billions of times in different orders and counts the forbidden outcomes.

In practice the best strategy is to simplify the code before testing it: AtomicLong, ConcurrentHashMap.merge, immutable objects. The concurrency test is just the safety net.