Ctech45
Ctech45

Reputation: 496

How to fix IllegalMonitorStateException

I am running into an IllegalMonitorStateException in my code and am not sure why I am receiving it and how to fix it. My current Code is and the error is happening in the try block:

  public static String scrapeWebsite() throws IOException {

    final WebClient webClient = new WebClient();
    final HtmlPage page = webClient.getPage(s);
    final HtmlForm form = page.getForms().get(0);
    final HtmlSubmitInput button = form.getInputByValue(">");
    final HtmlPage page2 = button.click();
    try {
    page2.wait(1);
    }
    catch(InterruptedException e)
    {
      System.out.println("error");
    }
    String originalHtml = page2.refresh().getWebResponse().getContentAsString();
    return originalHtml;
  }
}

Upvotes: 3

Views: 4519

Answers (2)

user2511414
user2511414

Reputation:

this is because page2.wait(1); you need to synchronize(lock) the page2 object then call the wait. also for sleeping it's better to use sleep() method.

synchronized(page2){//page2 should not be null
    page2.wait();//waiting for notify
}

the above code will not throw the IllegalMonitorStateException exception.
and note that like wait(), notify() and notifyAll() need to synchronize the object before notifying.

this link may help about the explanation.

Upvotes: 7

John Kugelman
John Kugelman

Reputation: 362087

If you're trying to just pause for a second, Object.wait() is the wrong method. You want Thread.sleep() instead.

try {
    Thread.sleep(1);  // Pause for 1 millisecond.
}
catch (InterruptedException e) {
}
  • sleep() pauses the current thread for the specified interval. Note that the time is specified in milliseconds, so 1 means 1 millisecond. To pause for 1 second pass 1000.

  • wait() is a synchronization-related method used to coordinate activity among different threads. It needs to be called from inside a synchronized block in tandem with some other thread calling notify() or notifyAll(). It should not be used to simply add a delay to your program.

Upvotes: 2

Related Questions