0

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)

Ian McGrath
  • 982
  • 2
  • 10
  • 23
  • 1. Nobody interrupted your thread. On what evidence have you concluded that? – Marko Topolnik Mar 31 '14 at 11:34
  • The exception I received? "java.lang.IllegalMonitorStateException" – Ian McGrath Mar 31 '14 at 11:35
  • Suggestion: go read the Javadoc of `Object#wait()`, maybe you get a clue. – Marko Topolnik Mar 31 '14 at 11:36
  • 2
    What does an `IllegalMonitorStateException` have to do with thread interruption? Maybe you just don't differentiate between "breaking" and "interrupting", but the latter is an official name of the mechanism which is not involved in your code. – Marko Topolnik Mar 31 '14 at 11:37
  • The question is... What are you waiting on ?. And yes, like marko says, where is the evidence that your thread was interrupted?. – TheLostMind Mar 31 '14 at 11:38
  • Sorry I had a brainfart. Now I cannot delete this question even though I want to. :( – Ian McGrath Mar 31 '14 at 11:40
  • possible duplicate of [IllegalMonitorStateException on wait() call](http://stackoverflow.com/questions/1537116/illegalmonitorstateexception-on-wait-call) – Raedwald Mar 31 '14 at 12:06

1 Answers1

7

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.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • Oh I feel like a fool. How could I forget this. I will delete my question. Of course, I will accept your answer. – Ian McGrath Mar 31 '14 at 11:39