# ThreadGuard

URL: https://deploy-preview-2977--selenium-dev.netlify.app/pt-br/documentation/webdriver/support_features/thread_guard/

---

> <p class="lead">
>   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:

```java
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:
```text
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:

* `protectedDriver` será criado no tópico principal
* Usamos Java `Runnable` para ativar um novo processo e uma nova `Thread` para executar o processo
* Ambas as `Thread`s entrarão em conflito porque a thread principal não tem `protectedDriver` em sua memória.
* `ThreadGuard.protect` lançará uma exceção.

#### Nota:

Isso não substitui a necessidade de usar `ThreadLocal` para gerenciar drivers durante a execução em paralelo.
