• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about wait() and notify()

 
Andres Gonzalez
Ranch Hand
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

My answer was that the code does not even compile because the call to notify()/wait() are not under a synchronized block. But it throws a runtime exception, which is fixed by adding the synchronized keyword to the doStuff() method.
So, when a wait()/notify()/notifyAll() are not placed under a synchronized block it'll throw a runtime exception, right? I just wanna make sure I'm concluding the right thing. There might be another reason and I haven't acknowledged ..yet..Any other observations will be highly appreciated.
thx
 
Dave Johnson
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Andres, the exception warning would be: java.lang.IllegalMonitorStateException: current thread not owner.
Which is the exception generated by code that uses wait() & notify() in non-synchronised blocks.
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is an example to show that wait() and notify() do not have to be declared in synchronized methods. But the threads that execute wait() and notify() must hold the lock on the object.


[ June 22, 2003: Message edited by: Marlene Miller ]
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Yes, right. Now, let�s describe what �placed under� means.
wait, notify and notifyAll may be invoked only by a thread that holds the
synchronization lock of the object on which the method is invoked.
The invocation can be made directly in a method or block of code declared as
synchronized, or can be made indirectly from a method invoked in such code.
Compliance generally cannot be verified at compile time. Failure to comply causes
these operations to throw an IllegalMonitorStateException at run time.
You can use the static method Thread.holdsLock(Object o) in your practice
programs to show you whether the current thread holds a lock.
[ June 22, 2003: Message edited by: Marlene Miller ]
 
Andres Gonzalez
Ranch Hand
Posts: 1561
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thx!!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic