39. Multi-Threaded Parallel Execution with ThreadLocal WebDriver

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:
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
}
}
}

Task

  • Implement ThreadLocalDriverManager:
  • 1. Provide static methods setDriver(WebDriver d), getDriver(), and clearDriver() using ThreadLocal<WebDriver>.
πŸ’‘Common doubts
Did you like the problem?
Lesson 39 of 44
Java
Loading code editor…
Next