ThreadGuard
Esta classe está disponível apenas no Java Binding
ThreadGuard verifica se um driver é chamado apenas da mesma thread que o criou. Problemas de threading, especialmente durante a execução de testes em paralelo, podem ter erros misteriosos e difíceis de diagnosticar. Usar este wrapper evita esta categoria de erros e gerará uma exceção quando isso acontecer.
O exemplo a seguir simula um conflito de threads:
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();O resultado mostrado abaixo:
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
Conforme visto no exemplo:
protectedDriverserá criado no tópico principal- Usamos Java
Runnablepara ativar um novo processo e uma novaThreadpara executar o processo - Ambas as
Threads entrarão em conflito porque a thread principal não temprotectedDriverem sua memória. ThreadGuard.protectlançará uma exceção.
Nota:
Isso não substitui a necessidade de usar ThreadLocal para gerenciar drivers durante a execução em paralelo.




