koralgooll koralgooll - 4 months ago 22
Java Question

Why Java throw java.lang.IllegalMonitorStateException when I invoke wait() in static way synchronized block?

I do not understand why Java throw exception from subject in this code. Could somebody explain me it?

class Wait implements Runnable
{
public void run() {
synchronized (Object.class) {
try {
while(true) {
System.out.println("Before wait()");
wait();
System.out.println("After wait()");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ObjectMethodInConcurency
{
public static void main(String[] args) {
Wait w = new Wait();
(new Thread(w)).start();
}
}

Answer

Use synchronized (this) { instead of synchronized (Object.class) in your class

EDIT

Reasoning behind the IllegalMonitorException in above code

In Java using synchronized keyword is a way to create and obtain a monitor object which will be used as lock to execute corresponding code block.

In the above code that monitor is "Object.class".

And wait() method tells the current thread to wait until it is notifyed and you have to invoke wait() on the monitor object which owns the lock.

So the way to invoke wait() method is like below otherwise you will get IllegalMonitorException.

synchronized(monitor){
    monitor.wait();
}

So for your example you can either use "Object.class.wait()" or change the monitor to this since you are calling wait() method on the current instance