Why must a call to wait() always be inside a while loop rather than an if statement?
There are two independent reasons. First, spurious wakeups: the JVM specification explicitly permits wait() to return even though notify() was never called, which can happen on certain OS and hardware combinations, so the waiting thread must re-check its condition after waking rather than assuming it is now true. Second, even when notifyAll() legitimately wakes every waiting thread, those threads still have to race each other for the lock -- the first one to acquire it may find the condition true and consume it, leaving the condition false again for everyone else. A while loop handles both cases correctly by re-checking the condition and calling wait() again if it is still false, whereas an if statement would let a thread proceed past a now-false condition and corrupt program state.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response