Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
}
like image 500
koralgooll Avatar asked Jan 15 '14 22:01

koralgooll


1 Answers

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

like image 88
Nu2Overflow Avatar answered Oct 11 '22 14:10

Nu2Overflow