Selenium + Java · Lesson 39 of 44

0/44 done

Module 39: Parallel Execution

39. Multi-Threaded Parallel Execution with ThreadLocal WebDriver

16 minlesson

Try it yourself

Implement ThreadLocalDriverManager:

  1. Provide static methods setDriver(WebDriver d), getDriver(), and clearDriver() using ThreadLocal<WebDriver>.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

ThreadLocal WebDriver Pattern

WebDriver is not thread-safe. If two parallel test threads share the same driver variable, they overwrite each other's commands and crash. ThreadLocal<WebDriver> ensures each thread has its own isolated instance:

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

    public static WebDriver getDriver() {
        return driverThread.get();
    }

    public static void setDriver(WebDriver driver) {
        driverThread.set(driver);
    }

    public static void quitDriver() {
        if (driverThread.get() != null) {
            driverThread.get().quit();
            driverThread.remove(); // Prevent memory leaks
        }
    }
}

Key Takeaways & Walkthrough Summary

Welcome to Phase 6! Running tests sequentially takes hours. In this lesson, you will master multi-threaded parallel execution using Java's ThreadLocal to provide each concurrent thread with its own independent WebDriver instance. Let's master parallel execution!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why is driverThread.remove() necessary after quit()?

ThreadPool executors reuse threads. Failing to call remove() can cause memory leaks and leftover state across test runs.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

Java
Skip