
While running Java program are you getting this error?
Exception in thread "main" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at crunchify.com.tutorial.CrunchifyJavaThreadPriority.main(CrunchifyJavaThreadPriority.java:50)
Today, while working on Java program I got above java.lang.IllegalMonitorStateException Exception at runtime. There wasn’t any error appeared during compile time. After finishing a complete Java program on threading when I ran the code, suddenly above error popped out.
Well, as exception stack trace clearly showed the line number from where exception appeared, I couldn’t found out the solution immediately. Exception was coming from below wait() statement.
try {
crunchChildThread.wait(10000); <==== from here
} catch (InterruptedException e) {
e.printStackTrace();
}
It turned out to be a missing synchronized block. In order for Thread.wait() to work, code block needs to be in synchronized block. This happens when you try to gain access without holding the Thread/Object lock.
In order to fix this just use below code. Make sure you use synchronized keyword for method.
private synchronized void generateThreadWait() {
final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
try {
println("Inside synchronized block entry..." + dtf.format(LocalDateTime.now()));
this.wait(10000);
println("Inside synchronized block exit..." + dtf.format(LocalDateTime.now()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Now re-run your program again and you shouldn’t see IllegalMonitorStateException exception any more.
