Conditional Queue

  • Help build efficient and responsive state-dependent classes
  • Conditional Variables are also called conditional queue. Why???
    • every thread which call lock.wait(), will want to wait for thread to notify
  • The lock object and the condition queue object must be the same
  • Implementation Pattern:
void foo() throws InterruptedException {
    synchronized (lock) {
        while (!conditionPredicate()) {
            lock.wait();
        }
        
        // do your logic
    }
}

wait(), notify() and notifyAll()

Condition Predicate

  • Precondition that makes an operation state-dependent
  • Example In Bounded Buffer:
    • take(): “buffer is not empty”
    • put(): “buffer is not full”
  • If condition predicate is not true, the operation just waits

ReentrantLock

  • Has Condition which has following methods:
    • await()
    • signal()
    • signalAll()

Interview Qs

Spurious wakeup

Missed signals

  • Always use notifyAll() since if you use notify() and you have more than one threads waiting then it will cause missed signal
  • See Risk of Threads

wait() vs sleep()

  • wait is for unspecified time, sleep for some specified time
  • wait releases the lock, sleep does not release the lock
  • wait works on condition, sleep works on time elapsed

wait() vs wait(timeout)

  • wait(timeout) waits for the specified time and resumes execution
  • wait() waits indefinitely until notify signal is received