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?