Ian McGrath
Ian McGrath

Reputation: 1012

Why do I get `IllegalMonitorStateException` exception

I have the following Java code:

public class Lean extends Thread   
{
    public static void main(String args[]) throws InterruptedException  
    {
        Lean lean = new Lean();
        System.out.println("starting");
        lean.start();
        lean.join();
        System.out.println("end");

    }

    public void run()
    {
        try
        {
            System.out.println("waiting");
            wait(20000);
        } 
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        finally
        {
            System.out.println("waiting finished");
        }
    }
}

Output is (keeps on changing -- sometimes I do not even see "end" printed )

starting
waiting
waiting finished
end
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at Lean.run(Lean.java:18)

Questions:

  1. Why do I get IllegalMonitorStateException exception?

  2. Why does thread.join not work the way it is expected to be? (I do not see see "end" printed sometimes)

Upvotes: 0

Views: 382

Answers (1)

Radiodef
Radiodef

Reputation: 37835

IllegalMonitorStateException is thrown when operations that require synchronization are called without holding the monitor lock. wait needs to be called in a synchronized block.

The documentation for wait covers this.

Basically you need to do:

synchronized(this) {
    wait();
}

This has nothing to do with the interruption mechanism.

Upvotes: 7

Related Questions