wait() java.lang.IllegalMonitorStateException: current thread is not owner

This error occurs when we try to wait on a web element.

Since wait(n) method causes the current thread to wait for n seconds, we have to make sure that the web element is not in use by any other thread.

To make sure that the web element object is accessed by only one thread at a time, enclose the WebElement.wait() method in a synchronized block.

The following is a simple code snippet where we enclose the wait() method in a synchronized block.

</>
Copy
synchronized (searchBox) {
	try {
		searchBox.wait(5000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

Example

Recreating the Exception

In the following program, we write Java code to open Google home page, find the first web element with the name "q" that is search box, enter a keyword "tutorialkart", wait for 5 seconds, and enter the RETURN key.

Java Program

</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://google.com/ncr");

        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("tutorialkart");
        
        try {
			searchBox.wait(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        
        searchBox.sendKeys(Keys.RETURN);
        driver.quit();
    }
}

Exception

Exception in thread "main" java.lang.IllegalMonitorStateException: current thread is not owner
	at java.base/java.lang.Object.wait(Native Method)
	at com.tutorialkart.seleniumtutorial.MyAppTest.main(MyAppTest.java:19)

Solution

To solve this issue, we surround the wait() method call in a synchronized block.

Java Program

</>
Copy
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class MyAppTest {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");  
    	WebDriver driver = new ChromeDriver();
        driver.get("https://google.com/ncr");

        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("tutorialkart");
        
        synchronized (searchBox) {
        	try {
        		searchBox.wait(5000);
        	} catch (InterruptedException e) {
        		e.printStackTrace();
        	}
        }
        
        searchBox.sendKeys(Keys.RETURN);
        driver.quit();
    }
}