ThreadGuard

このクラスは、Javaバインディングでのみ使用可能です。

ThreadGuardは、ドライバーが、それを作成した同じスレッドからのみ呼び出されることを確認します。 特に並行してテストを実行する場合のスレッドの問題は、不可解でエラーの診断が難しい場合があります。 このラッパーを使用すると、このカテゴリのエラーが防止され、発生時に例外が発生します。

次の例は、スレッドの衝突をシミュレートします。

    WebDriver protectedDriver = ThreadGuard.protect(startChromeDriver());

    Throwable[] caughtOnOtherThread = new Throwable[1];
    Runnable callFromOtherThread = () -> {
      try {
        protectedDriver.get("https://www.selenium.dev");
      } catch (Throwable t) {
        caughtOnOtherThread[0] = t;
      }
    };
    Thread otherThread = new Thread(callFromOtherThread);
    otherThread.start();
    otherThread.join();

結果は以下のとおりです。

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を使用して新しいプロセスを起動し、新しいスレッドを使用してプロセスを実行します
  • メインスレッドのメモリにprotectedDriverがないため、両方のスレッドが衝突します。
  • ThreadGuard.protectは例外をスローします。

注意:

これは、並列実行時にドライバーを管理するために ThreadLocalを使用する必要性を置き換えるものではありません。