Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a @RepeatedTest that runs a concurrency check 50 times, includes the repetition number in the display name and stops after 3 failures. What are the limits of this approach for flaky tests?

We write @RepeatedTest(value = 50, name = "{displayName} {currentRepetition}/{totalRepetitions}", failureThreshold = 3) and can inject RepetitionInfo to read the current repetition inside the test. Each repetition is a full test with its own @BeforeEach and @AfterEach, and after three failures the remaining repetitions are skipped. Repeating can reveal an intermittent failure, but 50 green runs do not prove there is no race; concurrency needs stress tools such as jcstress, and repeats must never be used to retry flaky tests until they pass.

Why this question is asked

Concurrency bugs are the classic intermittent failure: the code works 49 times out of 50 and fails on the fiftieth, depending on how the threads happen to interleave. @RepeatedTest is the JUnit 5 tool for running the same test many times, and interviewers ask about it to check two things: that we know its options, including the newer failure threshold, and that we understand what repetition can and cannot tell us. In this answer, we will write the concurrency check, configure the repeated test, look at what each repetition really runs, and then discuss the limits for flaky and concurrent code.

1The Code Under Test

Our example is a hit counter that is supposed to be thread-safe. The broken version uses a plain long field, so two threads can read the same value and both write back value plus one, losing an increment. That is called a lost update.

Java
class HitCounter {
private long hits; // broken: not atomic
void hit() { hits++; } // read, add, write: three steps
long hits() { return hits; }
}
class SafeHitCounter {
private final LongAdder hits = new LongAdder();
void hit() { hits.increment(); }
long hits() { return hits.sum(); }
}

2Writing the Repeated Test

The test starts 8 threads that each call hit() 1,000 times, waits for them, and expects 8,000. One run may well pass by luck, so we repeat it 50 times.

Java
@RepeatedTest(value = 50,
name = "{displayName} {currentRepetition}/{totalRepetitions}",
failureThreshold = 3)
@DisplayName("concurrent hits")
void countsEveryHit(RepetitionInfo info) throws Exception {
HitCounter counter = new HitCounter();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
CountDownLatch start = new CountDownLatch(1);
for (int t = 0; t < 8; t++) {
pool.submit(() -> { start.await(); for (int i = 0; i < 1000; i++) counter.hit(); return null; });
}
start.countDown(); // release all threads at once
} // close() waits for the tasks to finish
assertEquals(8000, counter.hits(),
"repetition " + info.getCurrentRepetition());
}
// concurrent hits 1/50 PASSED
// concurrent hits 2/50 FAILED expected: <8000> but was: <7412> repetition 2
// concurrent hits 3/50 PASSED
// concurrent hits 4/50 FAILED ...
// concurrent hits 5/50 FAILED ... (third failure)
// concurrent hits 6/50 .. 50/50 SKIPPED: failure threshold reached

The name pattern uses three placeholders: {displayName} is the method's display name, {currentRepetition} is the number of this run and {totalRepetitions} is 50. So every run appears separately in the report and we can see which ones failed.

RepetitionInfo is a parameter that JUnit injects into repeated tests. getCurrentRepetition() returns the number of this run, getTotalRepetitions() returns 50, and in newer versions getFailureCount() and getFailureThreshold() report how many runs have failed so far. Notice that the CountDownLatch releases all threads together, which makes the race more likely to show up; without it, the first thread might finish before the last one starts.

failureThreshold = 3 stops the waste: once three repetitions have failed, JUnit skips the rest, because we already know the code is broken. This attribute is newer than @RepeatedTest itself (it arrived in JUnit 5.10), so check your version.

3Each Repetition Is a Full Test

JUnit treats every repetition as its own test invocation. That means @BeforeEach and @AfterEach run around each of the 50 runs, a new test class instance is created for each one under the default lifecycle, and extensions such as Mockito's see 50 separate tests. That is usually what we want, since each run starts clean, but it also means that heavy setup in @BeforeEach is paid 50 times. In our test, a new HitCounter is created inside the method, so nothing leaks from one repetition to the next.

Step throughWhat JUnit runs for each repetition
  1. Create the test instance
  2. Run @BeforeEach methods
  3. Run countsEveryHit(info)info.getCurrentRepetition() = n
  4. Run @AfterEach methods
  5. Failures reached the threshold?
    YesSkip the remaining repetitionsNoStart repetition n + 1

5 steps in order. Play them, or step through them one at a time.

4The Limits of Repetition for Concurrency

Repetition finds intermittent failures only if the bad interleaving happens during one of the runs. With the broken counter it happens often, so a few runs out of 50 fail. But a subtler race might show up once in a million interleavings, or only on a machine with more cores, or only with a specific JIT optimisation, and then 50 green runs mean very little. Passing repetitions are evidence, not proof.

For real concurrency testing there are better tools. jcstress, the OpenJDK Java Concurrency Stress harness, runs small concurrent actions millions of times in carefully varied ways and reports every outcome it observed, including the ones the memory model allows but we did not expect. Stress tests with many threads and long runs, and model-checking tools such as Lincheck, go further still. And the strongest defence is design: using LongAdder, AtomicLong or a lock, so that the race simply cannot exist, as in SafeHitCounter.

5Do Not Use Repeats to Hide Flakiness

There is a misuse to avoid. Some teams see a flaky test and try to make CI green by running it several times and accepting the build if any run passes. That turns a signal about a real bug, often a race condition like ours, into noise. @RepeatedTest is for the opposite purpose: running a suspicious test many times, usually locally or in a dedicated job, to make it fail reliably so that we can find and fix the cause. When a fix is in place, a few hundred repetitions that all pass give reasonable confidence, and the repeated test can then go back to being a normal @Test.

6Follow-up questions

Can @RepeatedTest repetitions run in parallel?

They can when JUnit's parallel execution is enabled, because each repetition is a separate invocation. The failure threshold is only reliable when the repetitions run one after another, since parallel runs may already be in progress when the third failure is counted, so keep repeated tests sequential if the threshold matters.

What is the difference between @RepeatedTest and @ParameterizedTest?

@RepeatedTest runs the same test with the same inputs a fixed number of times, which is useful for nondeterministic behaviour. @ParameterizedTest runs it once per input from a source such as @ValueSource or @CsvSource, which is useful for covering different cases. They solve different problems.

Why does the test use a try-with-resources block on the ExecutorService?

Since Java 19, ExecutorService implements AutoCloseable, and close() waits for all submitted tasks to finish before returning. That makes sure every increment has happened before we read the counter, without writing shutdown and awaitTermination by hand.

7Conclusion

In this answer, we wrote a repeated concurrency test with @RepeatedTest(value = 50, name = "{displayName} {currentRepetition}/{totalRepetitions}", failureThreshold = 3), used RepetitionInfo to include the repetition number in the failure message, and saw that each repetition gets the full lifecycle. Repetition exposed the lost update in the broken counter, but we also saw its limits: passing runs do not prove a race is absent, jcstress and stress tests are the right tools for concurrency, and repeats should reproduce flaky failures, not paper over them.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write @RepeatedTest with value 50, a name of {displayName} {currentRepetition}/{totalRepetitions}, and failureThreshold 3, so each run shows up as, for example, concurrent hits 7 of 50, and once three runs have failed the remaining ones are skipped.

Then, if they want more

The failure threshold is a newer attribute, from 5.10, so I would check the version. Inside the test I can inject RepetitionInfo and call getCurrentRepetition to put the number in the assertion message.

The test itself starts eight threads behind a CountDownLatch so they all begin at the same moment, each increments the counter a thousand times, and then I assert 8000. Each repetition is a full test invocation, so @BeforeEach and @AfterEach run every time and I create fresh state per run.

On the limits: repeating only finds a race if the bad interleaving happens during the runs. Fifty passes are evidence, not proof, especially for rare races or ones that depend on core count. For real concurrency checks I would use jcstress or long stress tests, and design the code so the race cannot happen, for example with LongAdder.

And I would never use repeats in CI to retry a flaky test until it passes; repetition is for reproducing a failure locally so that we can fix it.

About this answer

Last updated
12 November 2026
Versions it names
JUnit 5, Java 19
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.
Official documentation
JUnit user guide
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 @RepeatedTest that runs a concurrency check 50 times, includes the repetition...": https://scrivio-interview-library.netlify.app/java/junit/dab714a698/