Selenium + Java · Lesson 39 of 44
Module 39: Parallel Execution
Try it yourself
Implement ThreadLocalDriverManager:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
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:
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
}
}
}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.
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.