• Post Reply Bookmark Topic Watch Topic
  • New Topic

wait, notify IllegalMonitorStateException  RSS feed

 
Markus Schmider
Ranch Hand
Posts: 147
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hallo!

I am trying to program a producer / consumer example. I am getting a IllegalMonitorStateException trying to call wait() although I have synchronized on the object I am calling wait() on.


What is wrong here? And what is the right way to implement this?

Thanks
 
Henry Wong
author
Sheriff
Posts: 22856
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am getting a IllegalMonitorStateException trying to call wait() although I have synchronized on the object I am calling wait() on.


Are you sure you are getting it for calling the wait() method? In order to use the notify() method, you also need to synchronized on the object.

Henry
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

Your wait() call looks OK, but your notify() call is unsynchronized and therefore will throw IllegalMonitorStateException .

Is this the right way to implement this? No, not exactly. Your consumer needs multiple nested loops, while your "producer" loop should include a wait() loop or messages may get lost. The pseudocode would look like



The idea is that the consumer has to tell the producer that the message has been consumed, or otherwise it may get overwritten. An alternative is to have a queue of messages that can hold more than one. The inner "while" loops account for the fact that wait() may wake up for the "wrong" reasons -- there are many possibilities, but suffice to say that coding this way is the right way to do things.
 
Markus Schmider
Ranch Hand
Posts: 147
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your kind help.
You're right:


fixes the problem. I didn't look any further than the wait() call, because the Exception Message pointed to it. Rookie mistake :-(
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!