QA Interview Hub · Knowledge base · Quizzes · Українська

Java Core › Parallelism

ThreadLocal<WebDriver> and shared state in parallel tests

A static WebDriver breaks a parallel run because the threads of one JVM share the same static fields and overwrite each other's driver. Every test needs its own state: an instance field (JUnit creates an instance per test method) or a ThreadLocal for static helpers, with a mandatory remove() after the test. Each test also needs its own data, such as a unique user.

Java · Concurrency

In a parallel run, test A suddenly works with the browser of test B. Where does that come from?

The tests passed one by one, then fell apart on four threads: "no such session", someone else's login on the page, random failures. The test code did not change, only the way it runs. This lesson explains why that happens and how to give every test its own state.

How it works and why. All threads of one JVM see the same static fields and the same objects on the heap. When a test keeps the driver in a static field, there is exactly one place for it in memory. Thread B writes its driver there, and thread A keeps commanding someone else's browser. The failure depends on thread order (a race condition), so it looks "floating": no repro on a two-core machine, a stable failure on a four-core CI.

Shared and own driver

Shared

static WebDriver

Every thread writes to one field: test A waits on a page while test B has already overwritten the driver and closed another browser.

Own

ThreadLocal<WebDriver>

Each thread sees its own driver: created in BeforeEach, closed and remove()d in AfterEach.

Figure 1. The root cause is not Selenium but shared mutable state: the fix gives every test its own copy.

The solution has three levels, from simplest to most subtle. First ask whether the test can simply own an object, and only then reach for ThreadLocal.

Who owns the state

1. Instance fielda new object per test2. ThreadLocala value per thread, for static helpers3. Separate dataown user and order per test
Figure 2. The higher a level sits in the list, the less hidden global state the project has.
  1. Instance field. JUnit 5/6 creates a new instance of the test class for every test method by default, so a non-static driver field is automatically owned by one test. TestNG uses one instance per class, and the field is shared by all its methods in parallel mode.
  2. ThreadLocal. Needed when the driver is fetched from static helpers, Page Objects or listeners that have no reference to the test instance. Each thread sees its own value of the variable.
  3. Separate data per test. Even with its own driver, two tests sharing one account interfere: one changes the password, the other cannot log in. Each test needs a unique user and entities.

Example: before → after. Typical code that works only sequentially:

public class LoginTest {
    static WebDriver driver;   // one field for all threads

    @BeforeEach
    void setUp() { driver = new ChromeDriver(); }

    @AfterEach
    void tearDown() { driver.quit(); }
}

The same with a driver per thread:

public final class DriverHolder {
    private static final ThreadLocal<WebDriver> DRIVER = new ThreadLocal<>();

    public static WebDriver get() {
        WebDriver d = DRIVER.get();
        if (d == null) throw new IllegalStateException("driver is not created");
        return d;
    }
    public static void start() { DRIVER.set(new ChromeDriver()); }
    public static void stop() {
        WebDriver d = DRIVER.get();
        if (d != null) d.quit();
        DRIVER.remove();   // mandatory: the thread goes back to a pool
    }
}

class LoginTest {
    @BeforeEach void setUp() { DriverHolder.start(); }
    @AfterEach  void tearDown() { DriverHolder.stop(); }
}

For JUnit to run tests in parallel at all, it is enabled in a settings file. By default everything runs in one thread:

# src/test/resources/junit-platform.properties
junit.jupiter.execution.parallel.enabled = true
junit.jupiter.execution.parallel.mode.default = concurrent
junit.jupiter.execution.parallel.config.strategy = fixed
junit.jupiter.execution.parallel.config.fixed.parallelism = 4

Every DriverHolder.get() now returns the driver of the thread running that test. stop() closes the browser and calls remove(): pools reuse threads, and without remove() the next test in the same thread sees a closed driver, while entries in a ThreadLocal hold memory.

Limits and alternatives.

  • A child thread does not see the parent's value. If a test starts its own threads (for example an ExecutorService for a race between two requests), pass the driver or client explicitly. InheritableThreadLocal copies the value only when a thread is created, so a pool that created its threads earlier will not pick it up.
  • ThreadLocal does not make WebDriver thread-safe: the driver stays a single-threaded object, it is just used by one thread.
  • ThreadLocal is hidden global state: it is hard to tell where the driver comes from. Where possible prefer an instance field or a parameter supplied by a JUnit extension.
  • Shared mutable state that cannot be removed (a counter, a token cache, a results list) is protected with thread-safe structures, which the next lesson covers.
  • Tests that truly cannot run in parallel (changing global settings of the environment) are marked with a resource: @ResourceLock in JUnit makes them run one at a time while the rest stays parallel.

Typical mistakes.

  • static WebDriver in a base class "because it is handier": the first parallel run breaks it.
  • A forgotten remove(): the pool hands the thread to the next test with an old closed driver or holds memory.
  • A shared test account: tests break each other even though the drivers differ.
  • Turning parallelism on without checking that the tests are independent: the order becomes random and a "green" run proves nothing.
  • Treating failures with longer timeouts or retries instead of looking for the shared state.

Check yourself

Why is a non-static driver field safe in parallel mode in JUnit 5/6 but not in TestNG?

Answer

JUnit creates a new instance of the class for every test method, so the field belongs to one test. TestNG by default uses one instance per class, and in parallel mode the methods of that class share one field.

What happens if AfterEach quits the driver but does not call ThreadLocal.remove()?

Answer

Pools reuse threads, so the next test in the same thread gets a closed driver instead of a new one (or the old value comes back), and the ThreadLocal entry holds memory. That is why remove() is mandatory.

A test starts its own ExecutorService and the pool tasks get null instead of the driver. Why?

Answer

ThreadLocal stores a value for one specific thread. Pool threads were created by another thread and have no value of their own, so get() returns null. Pass the driver or client into the task explicitly.

In the interview. Junior: In a parallel run all threads share static fields, so a static driver breaks: threads overwrite it. The fix: every test gets its own driver, either an instance field or a ThreadLocal<WebDriver> with a mandatory remove() after the test. Middle/Senior: First I ask what exactly is shared: the driver, the data or an environment resource. I give the driver as an instance field or a JUnit extension parameter, keep ThreadLocal for static helpers and clean it in a hook. Separate data per test (unique users), and tests that touch global state get @ResourceLock. I enable parallelism only when tests are independent, and I watch failures under CI load, not only locally.

More articles in this chapter