Only 48 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why call await() inside a while loop instead of inside an if  RSS feed

 
Alistair Parler
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I'm doing a bit of reading on the new JDK5 concurrency package. My question is:

Why do I have to do:



why can't I do this in an 'if':



As far as I can see, when another thread has fulfilled the condition which the blocked thread is waiting in (with signalAll()) then (providing that thread is aware of the okToProceed condition which it could do if both threads were under control of the same programmer) the 'if' construct would be good enough.

Is this just a belt-and-braces "you may aswell retest the expression again just to be on the safe side since you've already got the lock anyhow" test or am I missing something here?


Thanks in advance,
Alistair
 
Alistair Parler
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just had an idea:

is it because signalAll() will tell all threads in the wait-set to become runnable and therefore it's possible that one of the threads which was signalled has modified the state so that it's possible that it will spoil it for other threads? If that makes sense... Would we therefore not have the problem if we just used signal() to wake one thread (i.e. we could use the 'if' if we only used signal() from the condition-enabling thread)
 
Adam Smolnik
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pay attention to "spurious wakeup":

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

synchronized (obj) {
while (<condition does not hold>)
obj.wait(timeout);
... // Perform action appropriate to condition
}


from:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#wait()

and:
http://java.sun.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html#await()

Adam
 
Alistair Parler
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Adam - that clears things up for me!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!