Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
// Bad example of static variable, In this case the
// driver instance can be accessed by multiple threads and
// potentially can be changed by multiple threads.
// This results into an unexpected behaviour at runtime when
// this code runs in parallel
class WebDriverContainer
public static WebDriver driver; // No thread safety
// Keep in mind that a webdriver instance will be different for each thread.
// You cannot share the same instance to multiple tests running in different threads
// at the same time. This will result into unexpected results. What does it mean ?
// It means that we need to manage multiple instances of WebDriver for each thread.
// Here is an example to do this via a factory/manager class
class WebDriverManager
private static List<int, WebDriver> driverList = new ArrayList<int, WebDriver>(); // A better alternative could be ThreadLocal class
// GetDriver method is synchronized and is thread safe.
public static synchronised WebDriver GetDriver(String webdriverName)
// Firt get the threadID
int threadId = Thread.currentThread().getId()
// Check if the driverList already has a driver for this thread
return driverList.get(threadId);
// If we already dont have a webdriver instance for this thread
// we will create one and add in the List. After that we will return
// that instance of webdriver
WebDriver driver = new ChromeDriver();
driverList.add(threadId, driver);
return driver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment