Guarded waits, monitors and Condition
Definition:
A guarded wait suspends a thread until it can reacquire the lock and verify a condition.
Explanation:
A signal does not reserve a value or transfer ownership.
Illustration image:
Example:
lock.lockInterruptibly();
try {
while (items.isEmpty()) notEmpty.await();
return items.removeFirst();
} finally {
lock.unlock();
}Expected behavior. A spurious wakeup or a faster consumer cannot make this remove from an empty queue.
Internal working:
The waiter must reacquire the same lock and retest the predicate. A Condition allows independent wait sets for not-empty and not-full. ReentrantLock can provide interruptible or bounded acquisition. Always balance successful acquisition with a finally release.
Interview questions:
Why is a signal followed by another guard check?
Wakeups can be spurious, or another thread can take the item before the waiter reacquires the lock.