title: Why do threads spontaneously awake from wait()?
body: <p>I was wondering why threads spontaneously awake from wait() in java.<br>
  Is it a design decision? Is it a compromise?</p>
  
  <p>EDIT: (from Java Concurrency in Practice, p. 300)</p>
  
  <blockquote>
    <p><code>wait</code> is even allowed to return
    "spuriously" - not in response to any
    thread calling notify.</p>
  </blockquote>
  
  <p>Further the authors state:</p>
  
  <blockquote>
    <p>this is like a toaster with a loose
    connection that makes the bell go off
    when the toast is ready but also
    sometimes when it is not ready.</p>
  </blockquote>
  
  <p>This is why you always have to code like </p>
  
  <pre><code>synchronized(this){
      while(!condition)
          wait();
      }
  }
  </code></pre>
  
  <p>and never </p>
  
  <pre><code>synchronized(this){
      if(!condition){
          wait();
      }
  }
  </code></pre>
  
  <p>Even if the condition transitions only from 
  <code>false</code> to <code>true</code>. </p>