File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes wait( ) method behind the scene ... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "wait( ) method behind the scene ..." Watch "wait( ) method behind the scene ..." New topic

wait( ) method behind the scene ...

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830

This program is giving IlligalMonitorStateException , because I am not calling wait() method in synchronized context . But what actually the reason ?

can any body explain .

thanks a lot .
Subhash Bhushan C
Ranch Hand

Joined: Jan 27, 2005
Posts: 106
Every object, i.e., every object that extends Object, get associated with a "wait set", which is a set of threads. This wait set is manipulated by the wait(), notify() and notifyAll() methods of the Object class. The JLS specifies that, as per Java Thread scheduling mechanism, a thread can be added to a wait set of an object, only when the current thread holds a lock on the object. Meaning that, wait should be called for an object when the currently executing thread holds the lock on the object.

As to the reason of "Why" this is so, the programmers of Java might have experience problems with Thread scheduling mechanism, if the threads that call wait() on objects, did not own the locks on them.

Source: JLS 17.14

Regards,<br />Subhash Bhushan.
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830

Now , why this code is giving Exception , I am calling wait() method from synchronized block .

thanks a lot .
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
You have synchronized using the object h as monitor (a HasRun instance). You are calling wiat() using a different instance, t1 (a Thread). You can only call wait if you've synchronized on the same instance you're using to call wait. Thus, you need to do either


I'm not really sure what you're trying to do, so I don't know which is more appropriate.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: wait( ) method behind the scene ...
It's not a secret anymore!