0

I tought calling wait() then the thread loses the lock and has to regain it? Is this true? But obviously the Thread doesnt leaves the synchronized block. He is waiting on the same line where wait() was invoked and then moves on and doesnt has to re-enter the synchronized block?

Code Example:

  private int value;
  private boolean valueSet = false;

  public synchronized int get()
      throws InterruptedException {
    if (!valueSet) {  //should be while here
      this.wait();
    }
    valueSet = false;
    this.notifyAll();
    return value;
  }

  public synchronized void put(final int value)
      throws InterruptedException {
    if (valueSet) { //should be while here
      this.wait();
    }
    this.value = value;
    valueSet = true;
    this.notifyAll();
  }
}

I thought a Thread can only be inside the synchronized block if he has the lock?

simplesystems
  • 839
  • 2
  • 14
  • 28
  • and whats the benefit of the while loop? – simplesystems Jan 08 '18 at 19:33
  • ah I thought on wait() the thread is kicked out of the synchronized block, but thats not true right? it just moves on on the next line after wait() call? – simplesystems Jan 08 '18 at 20:35
  • After entering into waiting state there may be the chance that thread can wake up spuriously. So if block will fail here to put it back to waiting state if `valueSet` value is not changed yet, but if you use while loop then your thread will reenter to waiting block in case these unusual situation occurred. – sanit Jan 09 '18 at 02:50
  • @sanit the only thing i dont understand on wait(): the thread loses the lock but it is still inside the synchronized block?? – simplesystems Jan 09 '18 at 06:31

0 Answers0