ThreadGuard

此類別僅適用於 Java Binding

ThreadGuard 檢查驅動程式是否僅從建立它的同一個執行緒呼叫。執行緒問題,尤其是在平行執行測試時,可能會產生神秘且難以診斷的錯誤。使用此包裝器可防止此類錯誤,並在發生時引發例外。

以下範例模擬執行緒衝突

public class DriverClash {
  //thread main (id 1) created this driver
  private WebDriver protectedDriver = ThreadGuard.protect(new ChromeDriver()); 

  static {
    System.setProperty("webdriver.chrome.driver", "<Set path to your Chromedriver>");
  }
  
  //Thread-1 (id 24) is calling the same driver causing the clash to happen
  Runnable r1 = () -> {protectedDriver.get("https://selenium.programming.tw");};
  Thread thr1 = new Thread(r1);
   
  void runThreads(){
    thr1.start();
  }

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

下方顯示的結果

Exception in thread "Thread-1" org.openqa.selenium.WebDriverException:
Thread safety error; this instance of WebDriver was constructed
on thread main (id 1)and is being accessed by thread Thread-1 (id 24)
This is not permitted and *will* cause undefined behaviour

如範例所示

  • protectedDriver 將在主執行緒中建立
  • 我們使用 Java Runnable 來啟動新程序和新的 Thread 來執行程序
  • 兩個 Thread 將會衝突,因為主執行緒的記憶體中沒有 protectedDriver
  • ThreadGuard.protect 將拋出例外。

注意

這不能取代在平行執行時使用 ThreadLocal 來管理驅動程式的需求。