Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes IllegalMonitorStateException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "IllegalMonitorStateException" Watch "IllegalMonitorStateException" New topic
Author

IllegalMonitorStateException

Arnab Sadhukhan
Greenhorn

Joined: Sep 09, 2005
Posts: 6
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

Joined: Jan 19, 2006
Posts: 584
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 ?


"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
Arnab Sadhukhan
Greenhorn

Joined: Sep 09, 2005
Posts: 6
Hi Bessa,

Is there any way to call the wait() method in the above code?
Edisandro Bessa
Ranch Hand

Joined: Jan 19, 2006
Posts: 584
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: IllegalMonitorStateException