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

wait( ) method behind the scene ...

 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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

thanks a lot .
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

or

I'm not really sure what you're trying to do, so I don't know which is more appropriate.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic