title: Scala synchronized consumer producer
body: <p>I want to implement something like the producer-consumer problem (with only one information transmitted at a time), but I want the producer to wait for someone to take his message before leaving.</p>
  
  <p>Here is an example that doesn't block the producer but works otherwise.</p>
  
  <pre><code>class Channel[T]
  {
  private var _msg : Option[T] = None
  
  def put(msg : T) : Unit =
  {
      this.synchronized
      {
          waitFor(_msg == None)
  
          _msg = Some(msg)
  
          notifyAll
      }
  }
  
  def get() : T =
  {
      this.synchronized
      {
          waitFor(_msg != None)
  
          val ret = _msg.get
  
          _msg = None
  
          notifyAll
  
          return ret
      }
  }
  
  private def waitFor(b : =&gt; Boolean) =
      while(!b) wait
  }
  </code></pre>
  
  <p>How can I changed it so the producers gets blocked (as the consumer is) ?</p>
  
  <p>I tried to add another waitFor at the end of but sometimes my producer doesn't get released.</p>
  
  <p>For instance, if I have <code>put ; get || get ; put</code>, most of the time it works, but sometimes, the first <code>put</code> is not terminated and the left thread never even runs the <code>get</code> method (I print something once the <code>put</code> call is terminated, and in this case, it never gets printed).</p>