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.dokyumento.jp");};
  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 を使用する必要性を置き換えるものではありません。