# Synchronization in Selenium java

### ✅ What is Synchronization in Selenium (Java)?

---

### 🔹 **Definition:**

**Synchronization in Selenium (Java)** is the process of **matching the speed of your automation script with the speed of the web application** so that your script waits for the elements to **load, appear, or become ready for interaction** before performing actions on them.

---

### 🔹 **Why Synchronization is Needed:**

* Web elements may take time to load due to **AJAX, JavaScript, animations, or slow networks**.
    
* Without waiting, Selenium might try to interact with an element that:
    
    * is not yet present,
        
    * is not visible or clickable,
        
    * or is still being updated in the DOM.
        

This causes errors like:

* `NoSuchElementException`
    
* `ElementNotInteractableException`
    
* `StaleElementReferenceException`
    

### To avoid such kind of exceptions we using wait statements.

## **Types of Waits in Selenium**

Selenium provides 3 main types of waits:

| Wait Type | Use Case | Applies To |
| --- | --- | --- |
| **Implicit Wait** | Waits globally for elements to appear. | All elements |
| **Explicit Wait** | Waits for a specific condition on a specific element. | Single element or condition |
| **Fluent Wait** | Like Explicit Wait but allows polling and exception handling. | Advanced conditions |

---

## 1️⃣ **Implicit Wait**

> Tells WebDriver to wait for a certain amount of time when trying to find an element if it is not immediately available.

### 🔸 Syntax:

```java
javaCopyEditdriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
```

### 🔸 Key Points:

* Applies globally to all elements.
    
* Doesn't wait for a condition, only presence in DOM.
    
* Not recommended for dynamic web apps (use explicit instead).
    

---

## 2️⃣ **Explicit Wait**

> Waits for a **specific condition** (like visibility or clickability) before throwing an exception.

### 🔸 Common Conditions (ExpectedConditions):

* `visibilityOfElementLocated(By)`
    
* `elementToBeClickable(By)`
    
* `presenceOfElementLocated(By)`
    
* `alertIsPresent()`
    
* `titleContains(String)`
    
* `frameToBeAvailableAndSwitchToIt()`
    

### 🔸 Syntax:

```java
javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
```

---

## 3️⃣ **Fluent Wait**

> A more flexible version of Explicit Wait that allows:

* Custom polling interval
    
* Ignoring specific exceptions (e.g., `NoSuchElementException`)
    

### 🔸 Syntax:

```java
javaCopyEditWait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);

WebElement element = fluentWait.until(driver -> driver.findElement(By.id("username")));
```

---

## 📋 Full Cheat Sheet: Wait Type Comparison

| Feature | Implicit Wait | Explicit Wait | Fluent Wait |
| --- | --- | --- | --- |
| Applies To | All elements | Specific elements | Specific elements |
| Custom Conditions | ❌ | ✅ | ✅ |
| Polling Interval | Fixed | Fixed | Customizable |
| Exception Handling | ❌ | ❌ | ✅ |
| Recommended | ❌ (for dynamic apps) | ✅ | ✅ (advanced use cases) |

---

## 🧠 Best Practices

1. ✅ Prefer **Explicit Waits** over Implicit.
    
2. ❌ **Avoid mixing** Implicit and Explicit Waits → can lead to unexpected timeout behavior.
    
3. ✅ Use `ExpectedConditions` for readable and maintainable code.
    
4. ✅ Use **FluentWait** when:
    
    * You want custom polling intervals.
        
    * You want to ignore multiple exceptions.
        

---

## 💡 Example: Wait for Login Button to Be Clickable

```java
javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginBtn = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginButton")));
loginBtn.click();
```

---

## 🚨 Common Exceptions with Waits

| Exception | Reason |
| --- | --- |
| `TimeoutException` | Condition not met within timeout. |
| `NoSuchElementException` | Used without wait or condition wrong. |
| `StaleElementReferenceException` | DOM refreshed, element became stale. |

---

## 🧪 Bonus: Waiting for Page Load (JS Ready State)

```java
javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(webDriver -> ((JavascriptExecutor) webDriver)
    .executeScript("return document.readyState").equals("complete"));
```

---

Would you like a **downloadable PDF/Excel version** of this Waits Cheat Sheet or **sample framework code with all types of waits** implemented?

##### You said:

what is synchronization in java selenium

###### ChatGPT said:

### ✅ What is **Synchronization** in Selenium (Java)?

**Synchronization** in Selenium refers to **matching the speed of your automation script with the speed of the web application** so that your test scripts **do not fail due to timing issues**.

---

## 🚦 Why Synchronization is Needed?

Web applications are **dynamic**. Some elements take time to:

* Load
    
* Become clickable
    
* Appear/disappear
    
* Respond to JavaScript or AJAX calls
    

If Selenium tries to interact with an element **before it's ready**, it can throw exceptions like:

| Exception | Reason |
| --- | --- |
| `NoSuchElementException` | Element not yet in DOM |
| `ElementNotInteractableException` | Element not ready for interaction |
| `StaleElementReferenceException` | Element detached from DOM |

---

## 🛠️ Types of Synchronization in Selenium

### 🔹 1. **Implicit Wait** – Global sync

```java
javaCopyEditdriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
```

* Waits for element to appear in DOM.
    
* Works for all findElement calls.
    
* Not condition-based.
    

---

### 🔹 2. **Explicit Wait** – Targeted sync

```java
javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit")));
```

* Waits for specific condition.
    
* Better control than implicit wait.
    

---

### 🔹 3. **Fluent Wait** – Advanced sync

```java
javaCopyEditWait<WebDriver> fluentWait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);
```

* Custom polling.
    
* Ignore specific exceptions.
    

---

### 🔹 4. **Thread.sleep()** – Forced sync

```java
javaCopyEditThread.sleep(3000); // pauses execution for 3 seconds
```

* Pauses script no matter what.
    
* Not recommended (makes test slower and less reliable).
    

---

## 📊 Synchronization Comparison

| Type | Control | Dynamic? | Reliable? | Usage |
| --- | --- | --- | --- | --- |
| Thread.sleep | ❌ | ❌ | ❌ | Avoid |
| Implicit Wait | ❌ | ⚠️ | ⚠️ | Simple pages |
| Explicit Wait | ✅ | ✅ | ✅ | Recommended |
| Fluent Wait | ✅✅ | ✅✅ | ✅✅ | Complex scenarios |

---

## 📌 Example: Synchronization Failure Without Wait

```java
javaCopyEditdriver.findElement(By.id("searchBox")).sendKeys("laptop");  // Might fail if not loaded yet
```

## ✅ With Explicit Wait

```java
javaCopyEditWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement searchBox = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("searchBox")));
searchBox.sendKeys("laptop");
```

---

## 💡 Summary

| Term | Meaning |
| --- | --- |
| **Synchronization** | Matching script and app timing |
| **Goal** | Avoid timing-related failures |
| **Best Practice** | Use **explicit** or **fluent** wait (not `Thread.sleep`) |
