Monday, March 14, 2016

Why wait-notify should be called in a loop in a production environment?


From Java Documentation,

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
     } 
 
Some more deatils on spurious wakeup ca be found here.
 

No comments:

Post a Comment