| Author |
Question about wait() and notify()
|
Andres Gonzalez
Ranch Hand
Joined: Nov 27, 2001
Posts: 1561
|
|
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
|
I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
|
 |
Dave Johnson
Ranch Hand
Joined: May 25, 2003
Posts: 111
|
|
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
Joined: Mar 05, 2003
Posts: 1391
|
|
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
Joined: Mar 05, 2003
Posts: 1391
|
|
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
Joined: Nov 27, 2001
Posts: 1561
|
|
|
thx!!
|
 |
 |
|
|
subject: Question about wait() and notify()
|
|
|