Search code examples
javaspurious-wakeup

Why I can't check spurious wakeup by if condition instead of while loop


I'm currently reading Java The Complete Reference book, multithread section. There is an example about handling spurious wakeup. It's the classic producer-consumer example that I bring get() method here:

synchronized int get() {
    while(!valueSet)
        try {
            wait();
        } catch(InterruptedException e) {
            System.out.println("InterruptedException caught");
        }
    System.out.println("Got: " + n);
    valueSet = false;
    notify();
    return n;
}

Consider that I change the keyword while to if.

Even with spurious wakeup of the related thread the if condition will be checked. So I wonder why we should call to wait() within a loop?


Solution

  • Changing the while to an if would only check the condition before entering wait. Spurious wake-up refers to a situation where wait is entered and then returns without satisfying the condition. In this case valueSet could still be false when wait returns, so the check needs to be repeated.