jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads - wait() and notifyAll() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads - wait() and notifyAll()" Watch "Threads - wait() and notifyAll()" New topic

Threads - wait() and notifyAll()

Alan Martinez

Joined: Sep 17, 2009
Posts: 5

I'm having a little doubt about the following thread problem. It supposes that if I remove the call to the notifyAll() method on the line 39, the threads that keep awaiting, for the call to the wait() method on the line 14, shouldn't become runnable. So the line 17 couldn't be reachable, since the rules says: "A waiting thread will not return to runnable when the lock is released, unless a notification occurs.".

But, this doesn't happen. I remove the notifyAll(), the result is the same than with the notifyAll().

Waiting for calculation...
Waiting for calculation...
Waiting for calculation...
Total is: 4950
Total is: 4950
Total is: 4950

Could anybody please help me find out why this is happening?
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
Alan Martinez wrote: since the rules says: "A waiting thread will not return to runnable when the lock is released, unless a notification occurs.".

This rule is not always true.
Look here (javaspec): http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.8
2. Thread t does not execute any further instructions until it has been removed from m's wait set. The thread may be removed from the wait set due to any one of the following actions, and will resume sometime afterward.

* A notify action being performed on m in which t is selected for removal from the wait set.
* A notifyAll action being performed on m.
* An interrupt action being performed on t.
* If this is a timed wait, an internal action removing t from m's wait set that occurs after at least millisecs milliseconds plus nanosecs nanoseconds elapse since the beginning of this wait action.
* An internal action by the implementation. Implementations are permitted, although not encouraged, to perform "spurious wake-ups" -- to remove threads from wait sets and thus enable resumption without explicit instructions to do so. Notice that this provision necessitates the Java coding practice of using wait only within loops that terminate only when some logical condition that the thread is waiting for holds.

Also look here: http://en.wikipedia.org/wiki/Spurious_wakeup
Spurious wakeup is not covered by SCJP objectives, so don't bother your head with this right now.

I agree. Here's the link: http://aspose.com/file-tools
subject: Threads - wait() and notifyAll()
It's not a secret anymore!