Skip to content
javahacks.dev
JUnit

How to Run Tests in Parallel With JUnit 5 Safely and Fast

Turn on parallel test execution in JUnit 5: the configuration properties, execution modes, @Isolated and resource locks, and the shared state that breaks.

5 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the JUnit5, OpenJDK and Grafana logos.

Parallel tests cut feedback time when a suite is CPU or I/O bound, at the price of exposing every hidden dependency between tests. This uses JUnit Jupiter 6 on JDK 25. The flag file is described in configuring JUnit with properties.

Switch it on

src/test/resources/junit-platform.propertiesproperties
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = same_thread
junit.jupiter.execution.parallel.mode.classes.default = concurrent
junit.jupiter.execution.parallel.config.strategy = dynamic
junit.jupiter.execution.parallel.config.dynamic.factor = 1

With these settings, test classes run concurrently and the methods inside one class run in sequence. That is the safest useful start, because most shared state sits inside a class. Setting mode.default = concurrent also runs methods in parallel, and is the more aggressive step.

Modes at a glance

SettingMeaning
same_threadRun in the thread of the parent
concurrentRun in the fork join pool, alongside siblings
strategy = dynamicParallelism is factor times the processor count
strategy = fixedA set parallelism value

You can override per class or method:

java
@Execution(ExecutionMode.CONCURRENT)
class PricingTest { }

@Execution(ExecutionMode.SAME_THREAD)
class OrderedFlowTest { }

Protect shared resources

Some tests touch something global: a system property, a static cache, a file path, a port. Declare it, and JUnit will not run two tests that need the same lock together:

java
@ResourceLock(Resources.SYSTEM_PROPERTIES)
@Test
void readsProperty() { System.setProperty("mode", "x"); }

@ResourceLock(value = "orders-db", mode = READ_WRITE) locks any name you choose. A test that must have the whole JVM to itself is marked @Isolated.

Where parallel suites break

Static mutable state. A singleton cache or a counter changed by tests. Make it per test, or reset it in a callback.

Fixed ports and files. Two servers on 8080. Use port 0 and read the assigned port, or a @TempDir per test, see temporary directories.

Shared database rows. Tests that assume an empty table. Give each test its own schema or unique keys.

Order dependence. Tests that only pass in sequence are bugs, covered in test ordering.

Measure the gain

Compare wall time and CPU, since parallel runs help only when cores are idle during the run:

Shell
./mvnw -q verify

Run it a few times with and without the property. A suite dominated by one slow class will not speed up. Surefire can also fork several JVMs with forkCount, a different axis described in Surefire and Failsafe.

What speed-up to expect

Parallel execution is bounded by the machine, and by the part of the suite that cannot run in parallel. If a quarter of the run time is spent in tests that need exclusive access to a database, the best you can do is a four-fold improvement however many cores you have, and the real number is lower, since threads compete for memory and I/O. In a container with a CPU limit of two cores, the JVM sees the limit, and dynamic parallelism sizes itself to it, so a suite that ran in 8 minutes may drop to 5 and not to 1. Measure the sequential and the parallel run on the same machine, three times each, and keep the numbers in the pull request.

What breaks first

Tests that use static state, system properties, the default time zone or locale, environment access and the current directory all fail in parallel runs, in ways that look random. System.setProperty in a test changes it for every thread, and a test that sets a property, runs and clears it, can be interrupted by another that reads it. Mark such a test with @ResourceLock(Resources.SYSTEM_PROPERTIES) and JUnit serializes it against the others that declare the same lock, or with @Isolated to run alone. Better still, remove the global access by injecting the values.

Spring and parallel tests

Spring's test context cache is thread-safe, and tests that share a context also share its beans and its database. Two tests that insert rows with the same primary key into a shared database collide. Give each test its own data, such as a unique id from a counter, or roll back each test in a transaction, which isolates uncommitted changes in most databases. Tests that use @DirtiesContext force a rebuild of the context, which is slow in any mode and worse when threads wait for it.

Resources that must be per thread

A web driver, a temporary directory and a port are per-test resources. Use @TempDir, which gives each test its own directory, ask the operating system for a free port with port zero, and create a browser session per test and not per class. A shared port is the most common cause of intermittent Address already in use failures on CI.

Rolling it out

Turn on parallel execution for one module, with classes concurrent and methods in the same thread, which is the safest mode, and fix what breaks. Run the suite twenty times in a loop on CI to find flakiness before it reaches the team. Only then consider concurrent methods. Document the rules in the testing guide, so a new test is written to be independent from the start.

Reading a flaky failure from a parallel run

A parallel failure often prints a stack trace that is correct and misleading, because the test that failed is the victim and the one that caused it ran at the same time on another thread. Look at what ran concurrently: the report lists threads with names such as ForkJoinPool-1-worker-3, and the log lines carry the thread name if your pattern includes it. Find the other tests that touched the same resource in that window, and mark them with a lock. Rerunning the failing test alone usually passes, and that is the signature of shared state.

Keeping the setting stable

Put the parallel configuration in the platform properties file under version control, and note in a comment which package was fixed for it and when. If a new module joins the build, it does not inherit the flag until you add the file, which is a safe default. A suite that is parallel only on some developers' machines because of a local system property is the worst case, so check the configuration on CI first.

Where this does not apply

If tests share a real external system that cannot be partitioned, or the suite finishes in seconds, parallelism adds risk for little saving. The details are in the JUnit parallel execution guide and the Surefire parallel options, and the background in thread pool sizing.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.