Reputation: 1797
From the official Java Documentation of the class Condition
public void put(E x) throws InterruptedException {
lock.lock();
try {
while (count == items.length)
notFull.await();
items[putptr] = x;
if (++putptr == items.length)
putptr = 0;
++count;
notEmpty.signal();
} finally {
lock.unlock();
}
}
What is the role of having notFull.await()
in a while
loop? I am not seeing what this does. Can anyone provide a simple explanation?
Upvotes: 1
Views: 287
Reputation: 679
The reason for the while
loop is explained in the Condition documentation:
When waiting upon a Condition, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a Condition should always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop.
Upvotes: 2
Reputation: 28279
Suppose there are two waiting threads. Both get notified. Only one of them should move forward. Another have to re-check and wait.
Upvotes: 1