Skip to content

Instantly share code, notes, and snippets.

@virenv
Created November 13, 2018 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save virenv/0c2f263b33c100bcbd7cfc3d6597ba59 to your computer and use it in GitHub Desktop.
Save virenv/0c2f263b33c100bcbd7cfc3d6597ba59 to your computer and use it in GitHub Desktop.
// 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)
{
if(webdriverName.equals("Chrome")
{
// Firt get the threadID
int threadId = Thread.currentThread().getId()
// Check if the driverList already has a driver for this thread
if(driverList.has(threadId))
{
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