Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a test that tries to detect a lost-update bug in a Counter.increment() method by running many threads at once. Explain why a passing test does not prove the code is correct.

We start 16 threads from an ExecutorService, hold them at a CountDownLatch start gate so they all begin at once, let each call increment() 10,000 times, wait for all of them, and assert that the count equals 16 x 10,000 = 160,000; with a plain count++ the result is usually lower, which exposes the lost updates. We repeat the test many times to raise the chance of a bad interleaving. A passing run proves very little, though: it only shows that no failing interleaving happened in those runs, while some races need specific timing or hardware, so we combine such tests with reasoning, code review and tools such as jcstress for low-level code.

Why this question is asked

Writing a test for a race condition is a common interview exercise because it shows two things at once: whether we can coordinate threads correctly in a test, and whether we understand the limits of testing concurrent code. A candidate who writes the test and then claims the code is proven correct when it passes has missed half the question. In this answer, we will recap what a lost update is, build the test step by step with the reason for each part, watch it fail on a broken counter and pass on a fixed one, and then explain why a pass is weak evidence.

1A Quick Recap: Why count++ Loses Updates

The expression count++ looks like one operation, but it is three: read the current value, add one, write the result back. If two threads run it at the same time, both can read 41, both compute 42, and both write 42. Two increments happened, but the counter only moved by one. That is a lost update.

There is a second problem too. Without synchronization, the Java memory model does not promise that one thread sees another thread's writes promptly, and the JIT compiler may keep the value in a register. So the counter can be wrong in more ways than the simple interleaving above.

Java
class Counter {
private int count;
void increment() { count++; } // read, add, write: not atomic
int get() { return count; }
}
Step throughTwo increments, one lost
Thread Acount fieldThread B
read 41
read 41
write 42
write 42 (A's increment is lost)

4 messages in order. Play them, or step through them one at a time.

2Building the Test

A good concurrency test maximises the chance that threads overlap. If we simply submit tasks one after another, the first thread may finish its whole loop before the last one starts, and they never compete. So we use a start gate: a CountDownLatch with a count of one that every task waits on, and that the test opens once all tasks are ready. A second latch, or the futures, tell us when they have all finished.

Java
class CounterTest {
static final int THREADS = 16;
static final int ITERATIONS = 10_000;
@RepeatedTest(50) // run the whole scenario 50 times
void incrementsAreNotLost() throws Exception {
Counter counter = new Counter();
ExecutorService pool = Executors.newFixedThreadPool(THREADS);
CountDownLatch ready = new CountDownLatch(THREADS);
CountDownLatch start = new CountDownLatch(1);
try {
List<Future<?>> done = new ArrayList<>();
for (int t = 0; t < THREADS; t++) {
done.add(pool.submit(() -> {
ready.countDown(); // this thread is ready
start.await(); // wait for the gate to open
for (int i = 0; i < ITERATIONS; i++) counter.increment();
return null;
}));
}
ready.await(); // all 16 threads are waiting at the gate
start.countDown(); // open the gate: all begin together
for (Future<?> f : done) f.get(30, TimeUnit.SECONDS); // rethrows any failure in a task
assertEquals(THREADS * ITERATIONS, counter.get()); // expected 160000
} finally {
pool.shutdownNow();
}
}
}
// With the broken Counter: expected: <160000> but was: <151337> (varies per run)

Each part has a reason. The ready latch makes sure every thread has actually started before we open the gate, so none of them is still being created while others run. Calling f.get() instead of just waiting for the pool means an exception inside a task fails the test instead of disappearing. The timeout stops a deadlocked version from hanging the build forever. Future.get() also gives us a happens-before edge, so the main thread is guaranteed to see the counter's final value. And @RepeatedTest runs the scenario 50 times, because each run is one sample of the possible interleavings.

3Watching It Fail, Then Fixing the Counter

On a multi-core machine the broken counter usually fails on the first repetition, typically by a few thousand. Then we fix it. AtomicInteger performs the read, add and write as one atomic hardware operation, and for counters that are written far more often than read, LongAdder spreads the updates over several internal cells to avoid contention.

Java
class Counter {
private final AtomicInteger count = new AtomicInteger();
void increment() { count.incrementAndGet(); } // atomic read-add-write
int get() { return count.get(); }
}
// incrementsAreNotLost: 50 of 50 repetitions passed, 160000 each time

Notice that the same test now passes 50 times in a row. That is the moment to be careful about what we conclude.

4Why a Passing Test Does Not Prove Correctness

A concurrency test samples a few interleavings out of an astronomically large number. A pass means only that none of the interleavings that happened in those runs exposed a bug. A race that needs a thread to be preempted at one exact instruction, or that only appears when the JIT has compiled the method in a particular way after thousands of iterations, may not happen in 50 runs, or in 5,000.

Hardware matters too. x86 processors have a fairly strong memory model, so some reorderings that the Java memory model allows never happen there, while ARM processors, now common in cloud servers and laptops, reorder more freely. A test that passes every day on an x86 build agent can fail in production on ARM. Test machines with few cores also produce fewer real overlaps than a 64-core server.

So a test like this is a good detector, not a proof. It catches obvious bugs, and it protects against regressions, for example someone replacing the AtomicInteger with a plain int later. Correctness must also come from reasoning: is every shared variable protected by the same lock, or atomic, or immutable? Is every compound action atomic? A code review by someone experienced with concurrency asks exactly those questions. For low-level code, such as custom lock-free structures or code that relies on volatile and ordering, the jcstress tool from OpenJDK runs tiny concurrent scenarios millions of times with many thread arrangements and reports every outcome it observed, which explores far more interleavings than a unit test.

What each technique gives us
TechniqueWhat it showsLimit
Stress unit test like this oneCatches frequent races and regressionsPass does not prove absence
@RepeatedTest, more cores, ARM agentsMore interleavings and orderingsStill a sample
Reasoning and code reviewWhether shared state is protectedDepends on reviewer skill
jcstressOutcomes of tiny scenarios, millions of runsSmall snippets only

5Follow-up questions

Why not use Thread.sleep to make the threads start together?

Because sleeping does not coordinate anything; it only hopes. Threads still start at different times, and the test becomes slow and timing-dependent. A CountDownLatch start gate releases all waiting threads at the moment the main thread counts it down, which is both faster and far more reliable.

Would a volatile int fix the counter?

No. volatile guarantees that every thread sees the latest written value and prevents some reorderings, but count++ on a volatile is still read, add, write, and two threads can still read the same value. The test would still fail. We need an atomic operation such as AtomicInteger.incrementAndGet or a lock around the increment.

How many threads and iterations should such a test use?

Enough threads to exceed the number of cores, so the scheduler preempts threads in the middle of their work, and enough iterations that the loops overlap for a meaningful time, which 10,000 usually achieves. More is not always better, because a very long test gets skipped or flaky under CI load; a few hundred milliseconds per repetition and dozens of repetitions is a reasonable balance.

6Conclusion

In this answer, we saw that count++ is a read, an add and a write, so concurrent increments can be lost. We built a test with a fixed pool of 16 threads, a ready latch and a start gate so all threads compete at once, 10,000 increments each, futures with a timeout to surface errors, and an assertion of 160,000, repeated 50 times. It failed on the broken counter and passed on AtomicInteger. We then saw why the pass is weak evidence: it samples a few interleavings, depends on timing, core count and hardware, and must be combined with reasoning, review and jcstress.

What to say in the interviewAbout 100 seconds aloud

Open with

I would write the test with an ExecutorService of 16 threads and two CountDownLatches: a ready latch that each task counts down when it starts, and a start gate with a count of one that every task waits on.

Then, if they want more

Once all sixteen are ready, the test opens the gate so they all hit increment at the same moment, which maximises overlap. Each task calls increment 10,000 times.

I collect the futures and call get with a timeout, so an exception in a task fails the test and a deadlock does not hang the build, and then assert that the count is 16 times 10,000, 160,000. I would mark it as a repeated test, say 50 repetitions, because each run is just one sample of possible interleavings.

With a plain count++ it typically fails with something like 151,000, since count++ is a read, an add and a write and two threads can read the same value. Switching to AtomicInteger or LongAdder makes it pass. But a passing test does not prove the code is correct.

It only shows that the interleavings that happened in those runs were fine. Some races need an exact preemption point, a particular JIT compilation, more cores, or a weaker memory model like ARM's compared with x86.

So I treat the test as a detector and a regression guard, and rely on reasoning and review for correctness, checking that every shared variable is atomic, locked or immutable. For low-level code I would use jcstress, which runs tiny concurrent scenarios millions of times and reports every outcome.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a test that tries to detect a lost-update bug in a Counter.increment() method by...": https://scrivio-interview-library.netlify.app/java/concurrency-problems/98f5faef35/