• Selenium Video Tutorials

Selenium WebDriver - ThreadGuard



The ThreadGuard class is only applicable to Java Binding. It is used to ensure that a driver is invoked from the same thread from where it originated. Multiple Threading problems are encountered while running the tests in parallel mode, and those are sometimes not very easy to debug and find the root cause of the errors. With the help of the ThreadGuard wrapper, we can avoid those issues and generate the correct exception at the proper time.

Example

public class DriverParallel {

   //Thread main (id 1) created this driver
   private WebDriver pDriver = ThreadGuard.protect(new EdgeDriver()); 

   //Thread-1 (id 14) is calling the same driver resulting in error
   Runnable run1 = () -> {
      protectedDriver.get("https://www.tutorialspoint.com/selenium/practice/accordion.php");
   };
   Thread thread1 = new Thread(run1);

   void runThreads(){
      thread1.start();
   }

   public static void main(String[] args) {
      new DriverClash().runThreads();
   }
}

The above code would give an exception. Here, the pDriver would be created in the Main thread. The Runnable class is used to introduce a new process and a new thread. Both of them would encounter issues since the main thread is devoid of pDriver in its memory. Hence threadGuard.protect would generate an exception.

Thus, in this tutorial, we had discussed ThreadGuard using the Selenium Webdriver.

Advertisements