I was wondering why threads spontaneously awake from wait() in java.
Is it a design decision? Is it a compromise?
EDIT: (from Java Concurrency in Practice, p. 300)
waitis even allowed to return
“spuriously” – not in response to any
thread calling notify.
Further the authors state:
this is like a toaster with a loose
connection that makes the bell go off
when the toast is ready but also
sometimes when it is not ready.
This is why you always have to code like
synchronized(this){
while(!condition)
wait();
}
}
and never
synchronized(this){
if(!condition){
wait();
}
}
Even if the condition transitions only from
false to true.
These spontaneous wakeups are also called “spurious wakeups”. In the Java specification, the spurious wakeups are permitted (though not encouraged) for jvm implementations.
The reason they are permitted is because many implementations may be based on pthreads (POSIX threads), that have this behaviour. Why?
Wikipedia: