Reputation: 5
For example if I have this code :
public synchronized T get() throws Exception {
while (!condition()) {
try {
wait();
} catch (Exception e) {
throw new Exception(e);
}
if (!condition()) {
throw new Exception();
}
}
...
}
Can I switch the while by if?
Upvotes: 0
Views: 45
Reputation: 58888
Yes, it is necessary.
For one thing: perhaps the following happens:
Now thread 2 shouldn't just assume the condition is true, because it's not!
For another thing, spurious wakeups are possible. This means wait
might return for no reason at all (or no reason relevant to your program) - for instance, it might return if a debugger attaches to your program.
Upvotes: 1