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

Java Core › OOP in a framework

Interfaces, final, static and why a static driver breaks parallel runs

A static field has one instance per class, so in a parallel run all threads share a single driver. Tests overwrite each other's driver and one test's quit() closes everyone's browser. JUnit 5 creates a new instance per test method by default, so a non-static field is safe. For static code use ThreadLocal with a mandatory remove(); keep only constants and stateless utilities static.

Java · OOP

The tests are green on one thread, but with parallelism 4 the browser windows click on each other. One variable is to blame.

A team turns on parallel execution to cut a run from forty minutes to ten. The first runs become unstable: a login test suddenly sees the cart page, another gets NoSuchSessionException because a neighbouring test has already closed its browser. The errors differ each time, and they cannot be reproduced on one thread. The base class contains the line protected static WebDriver driver;.

This lesson covers how static, final and access modifiers work, why a static field with state breaks parallelism and what to replace it with. Interfaces are covered as a way to keep the choice of implementation outside the tests.

How it works and why it is designed so

static means "belongs to the class, not to an object". The field exists in one copy per class within a JVM (strictly, per class loader), and all threads see the same value. A non-static field exists separately in every object. Hence it matters how many tests share one variable.

By default JUnit 5 creates a new instance of the test class for every test method (the PER_METHOD lifecycle). A non-static driver field then belongs to one test, and even if methods run in parallel (junit.jupiter.execution.parallel.enabled=true), they do not touch someone else's browser. A static field exists in one copy per class, so every test overwrites the previous test's driver, and one quit() closes everyone's browser. The declaration did not change, the number of threads did, which is why the code "worked" for years.

public class BaseTest {
    protected static WebDriver driver;     // one field for the whole JVM

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

    @AfterEach
    void stopBrowser() { driver.quit(); }  // closes everyone's browser
}

Where the driver variable lives

static

One variable per JVM

Tests A and B on different threads write to the same variable: B overwrites A's browser, and A's quit() closes B.

Instance field

A variable per test

JUnit creates an object per method; each has its own browser and the threads do not cross.

Figure 1. State in a static is shared by all threads.

There are two ways to fix it. The first is simple: remove static and pass the driver to pages through a constructor (see the previous lesson). The second is needed when the driver must be fetched from a static place, such as a utility or Cucumber steps with no access to the instance: then ThreadLocal gives each thread its own value.

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

    private DriverManager() {}                    // a utility, no instances

    public static void start() { DRIVER.set(DriverFactory.create(Config.browser())); }

    public static WebDriver get() {
        WebDriver driver = DRIVER.get();
        if (driver == null) throw new IllegalStateException("Driver not started in " + Thread.currentThread().getName());
        return driver;
    }

    public static void quit() {
        WebDriver driver = DRIVER.get();
        if (driver != null) { driver.quit(); DRIVER.remove(); }  // remove: pool threads live on
    }
}

Here the static variable is final and only holds the "key"; the value lies separately for each thread. The remove() call is mandatory: thread pools reuse threads, so a forgotten value reaches the next test, and in a long process it also holds memory. ThreadLocal has its own lesson in the parallelism section.

Another "static" warning: not only the driver. Static variables with the current user, a token, a counter or a list of created data behave the same way. Only static constants (static final of an immutable type) and stateless utilities such as date formatting are safe.

final and access modifiers

final has three meanings. A variable: it can be assigned once, but for a reference this forbids reassignment, not changing content (a final List can be added to). A method: it cannot be overridden. A class: it cannot be extended (String is like that). An immutable class (a final class with final fields of immutable types) is safe to share between threads without locks, which is why records suit shared data.

Access modifiers from narrower to wider: private (the class only), none (the package), protected (the package and descendants), public (everyone). The narrower the access, the freer you are to change the implementation without breaking tests. In addition, in BaseTest keep driver as private with a getDriver() method or pass it through a constructor, so that descendants do not overwrite it by accident.

Interfaces

An interface is a contract without state: what an object can do, with no tie to an implementation. A class implements several interfaces but extends only one class. Where a framework has interchangeable implementations, an interface fits: DriverFactory for a local run and for Grid or a cloud, TestDataProvider from a file or from an API. A test depends on the interface, and configuration picks the implementation. A default method (Java 8) gives a default implementation, a static method in an interface suits a factory, and a private method (Java 9) shares code between default methods. An abstract class is chosen when you need shared state and a share of ready code.

Limits and alternatives. A non-static field helps only with the PER_METHOD lifecycle. If somebody turned on @TestInstance(Lifecycle.PER_CLASS), all methods of the class share one instance, and so one field, and with parallel method execution the problem returns. Another important detail: parallelism through several processes (Surefire forkCount above one) gives each process its own static variables, so a static driver "does not break" there, but moving to threads will break it. So it is safer to write code that does not depend on the run mode.

Common mistakes

  • static WebDriver in a base class or on a page: works on one thread, breaks on two.
  • A static user or token changed by one test: neighbouring tests fail with foreign data.
  • ThreadLocal without remove(): the value leaks between tests that run on the same thread.
  • A final List considered immutable: its content changes, and shared data with it.
  • An interface per class "just in case", though there is one implementation and it will not change.

Check yourself

Why did tests with static WebDriver work sequentially and start to break only with parallel execution?

Answer

Sequentially a test finishes (and closes the driver) before the next one starts, so the shared variable is never used by two tests at once. In parallel, two threads write and read the same field, and one test closes the other's browser.

What does final List<String> names = new ArrayList<>(); mean, and can you call names.add("x")?

Answer

You can: final only forbids assigning a different list to the variable. The content changes. For true immutability use List.of(...) or List.copyOf.

Why is remove() needed after ThreadLocal.set in a test thread?

Answer

Pool threads are reused: without remove() the next test on the same thread would see the previous, closed driver, and the value keeps occupying memory.

In an interview. Junior: static belongs to the class, not an object, so it is shared by all threads. A static driver breaks in parallel tests: they overwrite each other's. The fix: a non-static field or ThreadLocal. Middle/Senior: JUnit 5 creates an instance per method, so a non-static field is safe until PER_CLASS is turned on. If the driver is needed from static code, I use ThreadLocal with a mandatory remove(), because pool threads live on. I keep only constants and stateless utilities static, and move the choice of implementations (local, Grid, cloud) into an interface and configuration.

More articles in this chapter