Monday, August 27, 2012

java spurious wakeups

What are spurious wakeups ?
In java , a thread t is put into waitset of an object 'a' by calling a.wait();
To be selected to be removed from a's waitset , there should be a call to a.notify / a.notifyAll from another thread.This is an example for explicit wake up(Which most programmers are aware of and think that this is the only possible way to wake up a waiting thread).

Note from JLS :
 An internal action by the implementation. Implementations are permitted, although not encouraged, to perform "spurious wake-ups", that is, 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.

 What it means ?
JVM implementation are given flexibility to wakeup a thread even when there is no explicit calls to either notify or notifyAll.Such wakeups, which are possible , are called spurious wakeups.

Consider the following code , for simplicity sake removed try catch blocks:

void method(){
  synchronized(a){
      if(cond / buffer empty){
         a.wait() ;
         //do some task asuming buffer is not empty.
      }
  }
}

In JVM where spurious wakeups are possible, consider the the case when the thread t is woke up spuriously , the following task assuming that buffer is not empty might break the program.

We have written the code assuming that there are no spurious wakeups allowed.Our code is sure to break in environments where such wakeups are allowed.Our code is not guarded.

So when writing code that waits guard your programs against spurious wakeups,

void method(){
  synchronized(a){
      while(cond / buffer empty){
         a.wait() ;
      }
      //do some task asuming buffer is not empty.
  }
}

In the above code, even when a thread is spuriously woke up, if the condition is  not met we are gonna wait again guarding us against spurious wakeups.

No comments:

Post a Comment