koralgooll koralgooll - 1 year ago 109
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()");
System.out.println("After wait()");
} catch (InterruptedException e) {

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

Answer Source

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


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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download