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

Selenium + Java › Framework and runs

Parallel runs: a driver per thread, isolation, CI

WebDriver is not thread-safe, so a parallel run needs a separate driver per thread, created before the test and closed after it. A static driver is replaced with ThreadLocal plus remove(), or with a driver in a fixture. This is only half of isolation: tests must not share accounts and data, and unique data is created per test, preferably through an API.

Selenium · Parallelism

Parallel execution was turned on and tests began clicking in someone else's browser. Why?

The suite took forty minutes and the team turned on four threads. Instead of ten minutes it turned into a lottery: the login test checks the cart, the cart clicks in another test's tab, and the report shows random failures that cannot be reproduced in a single run. The test code did not change, only the way of running did. The lesson covers why a WebDriver cannot be shared between threads, how to organise a driver per thread and what else must be isolated so that parallelism speeds the suite up rather than breaking it.

How it works and why. WebDriver is not thread-safe: it is a single session with one current window and one page state. Two commands from different threads into the same session get interleaved: one test has already moved to a new page while another looks for an element of the old one. Hence one rule of parallelism: one driver per test (thread), created before the test and closed after it. Tests inside one thread run in turn, and nothing is shared between threads.

Example: from static to ThreadLocal. The typical trap:

public abstract class BaseTest {
    protected static WebDriver driver;          // shared by all threads

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

    @AfterEach
    void stop() { driver.quit(); }              // closes someone else's browser
}

A static field is one per process, so five threads overwrite a single reference. Each @BeforeEach creates a new browser, but a moment later all tests act on the last one created, and one test's quit() closes another's browser. The symptoms vary: NoSuchSessionException, actions on someone else's page, hangs. The fix: keep the driver in a ThreadLocal so that each thread sees its own instance:

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

    public static WebDriver get() { return DRIVER.get(); }
    public static void start() { DRIVER.set(new ChromeDriver()); }
    public static void stop() {
        WebDriver d = DRIVER.get();
        if (d != null) { d.quit(); }
        DRIVER.remove();                         // do not leave a value in the thread pool
    }
}

abstract class BaseTest {
    @BeforeEach void start() { Browser.start(); }
    @AfterEach  void stop()  { Browser.stop(); }
}

remove() after the test is needed because pool threads outlive a test, and the old value would stay for the next one. A simpler alternative, if Page Objects are created in the test: create the driver in a fixture and pass it through the constructor (the lesson “Page Object Model: what it is and the rules”), with no global state. In JUnit 5 it is convenient to make the driver an extension with a ParameterResolver that creates and closes it for each test.

One driver for all or one per thread

Wrong

static WebDriver

All threads overwrite one reference and drive someone else's browser. Failures are random and not reproducible alone.

Right

ThreadLocal<WebDriver>

Each thread has its own browser and closes it itself. Tests do not see one another.

Figure 1. Parallelism is safe when no Selenium state is shared between threads.

How to turn parallelism on. In JUnit 5 these are properties in junit-platform.properties:

# 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

In TestNG the attributes parallel (methods, classes or tests) and thread-count in testng.xml:

<suite name="ui" parallel="methods" thread-count="4">
  <test name="regression">
    <packages><package name="tests.*"/></packages>
  </test>
</suite>

There is also process-level parallelism: Maven Surefire with forkCount starts separate JVMs, each with its own static fields. It isolates better but costs more memory.

Data isolation and CI. A driver per thread solves only half of the problem. Tests must not share accounts, orders, files and queues: otherwise one changes data another relies on, and flaky failures appear that are invisible in a single run. The most reliable way is to create unique data per test, preferably through the API rather than the interface:

// unique data per test: no shared accounts and orders
String email = "qa+" + UUID.randomUUID() + "@example.com";
api.createUser(email, "Secret123!");       // setup through the API
new LoginPage(Browser.get()).loginAs(email, "Secret123!");

The number of threads is matched to resources: Grid slots (the lesson “Selenium Grid 4 and Docker: how it is built and how to run it”), the CPU and memory of the CI runner, and the ability of the environment itself to withstand parallel requests. In CI usually: headless or Grid in a container, the Selenium Manager cache between runs, artifacts (screenshots, logs, a report) kept even for failed jobs, and a rerun of only the failed tests marked as flaky in the report, not hidden.

Limits and alternatives. Parallelism does not cure slow tests, it only hides them behind a number of threads; first it is worth removing redundant interface steps (login through the API, data setup without the UI). It also does not work if tests depend on order. Sometimes it is simpler to split the suite into several CI jobs than to divide it among threads of one process: isolation is complete and failures are easier to reproduce. If the environment is single and weak, more threads give more timeouts, not more speed.

Common mistakes.

  • static WebDriver in a base class or Page Object: parallel threads drive someone else's browser.
  • ThreadLocal without remove(): the value stays in a pool thread and gets into the next test.
  • A shared test account: one test changes a password or a cart and another fails for an unclear reason.
  • More threads than Grid slots or runner cores: a queue and timeouts instead of speed-up.

Check yourself

After moving to ThreadLocal<WebDriver>, the second test in the same thread sometimes starts with old cookies, and Browser.get() creates the driver lazily, only when the thread has none yet. What is missing in the teardown?

Answer

quit() or remove() was not called: the driver from the previous test stayed in the pool thread and get() hands it out. The teardown must close the driver (quit) and clear the value (remove), and the start creates a new one.

Tests passed in parallel 20 times in a row locally, yet on CI they sometimes fail when two tests change the cart of one account. What should be done instead of reducing threads?

Answer

Remove the shared state: create a unique account and data for each test (through the API or with a UUID in the name) and clean up afterwards. Reducing threads only lowers the chance of a collision and does not remove the dependency.

In an interview. Junior: WebDriver is not thread-safe, so parallel tests need a separate driver per thread: I create it before a test and close it with quit() after. Middle/Senior: I replace a static driver with a ThreadLocal with remove() or with a fixture-held driver passed through the constructor. I enable parallelism through JUnit properties or testng.xml, and I also ensure data isolation: unique accounts and orders per test, setup through the API. I match threads to Grid slots and runner resources.

More articles in this chapter