QA
Mid-level QAFrameworks & Design PatternsFree question

How do you run Selenium tests in parallel safely? What is ThreadLocal?

60-second answer

Parallel execution needs every test thread to have its own WebDriver and its own data. If the driver is a static field, threads overwrite each other and close each other's browsers. ThreadLocal solves this: it gives each thread its own copy of a variable. I wrap the driver in a ThreadLocal inside a DriverManager with set, get and quit methods, and always call remove after quitting to avoid memory leaks in thread pools. Then I enable parallel methods or classes in testng.xml and make sure tests don't share accounts or data.

Explanation

Checklist for parallel-safe tests:

  • ThreadLocal driver (or a new driver instance passed through fixtures).
  • No static mutable state (shared lists, counters, page objects).
  • Unique test data per test (unique emails, separate accounts).
  • Thread-safe reporting (ExtentTest in ThreadLocal too).
  • Tests don't depend on order.
  • Enough Grid capacity or machine resources.

Example

After moving to a ThreadLocal driver and per-test users created via API, a 400-test suite ran with 8 threads in 25 minutes instead of 3 hours, with no cross-test interference.

Sample code

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

    public static void set(WebDriver driver) { DRIVER.set(driver); }
    public static WebDriver get() { return DRIVER.get(); }

    public static void quit() {
        WebDriver d = DRIVER.get();
        if (d != null) {
            d.quit();
            DRIVER.remove();   // avoid leaks in thread pools
        }
    }
}