Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

IllegalMonitorStateException

 
Arnab Sadhukhan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class t extends Thread{

int i=0;

public static void main(String argv[]){
t w = new t();
w.start();
}

public void run(){

while(true){
try{
wait();

}catch (InterruptedException e) {}
i++;
}//End of while

}//End of amethod
}//End of class
While running this program it is throwing IllegalMonitorStateException, why?
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Arnab,

In order to call wait method you HAVE to have the lock on object that given object, otherwise, you will get an IllegalMonitorStateException.

One more thing ...

Taking a close look at your code, I think that if it ran, your code still would be waiting indefinitelly because you're calling wait on the same object which represents the thread, so, who will notify your thread ?
 
Arnab Sadhukhan
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bessa,

Is there any way to call the wait() method in the above code?
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Arnab,

I'm going to use an example extracted from K&B book which explains in a very simple way how to use wait method on thread having a lock on another object.

You can find this example in K&B Study Guide for Java 5 on page 721.

Here we go ...


This program contains two objects with threads: ThreadA contains the main
thread and ThreadB has a thread that calculates the sum of all numbers from 0 through 99. As soon as line 4 calls the start() method, ThreadA will continue with the next line of code in its own class, which means it could get to line 11 before ThreadB has finished the calculation. To prevent this, we use the wait() method in line 9.

Notice in line 6 the code synchronizes itself with the object b�this is because in order to call wait() on the object, ThreadA must own a lock on b. For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object.

When the thread waits, it temporarily releases the lock for other threads to use, but it will need it again to continue execution.

Hope that helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic