Condition Variables - Inter-Thread Communication
1. The “Why” Sometimes a thread has the lock but cannot proceed because the data isn’t ready (e.g., a Consumer finds an empty queue). The Problem: If the thread just loops (while(queue.isEmpty());), it wastes 100% of the CPU. The Solution: The thread “waits” on a condition. This releases the lock and puts the thread to sleep. When another thread makes the condition true, it “signals” (notifies) the sleeping thread to wake up and try again. 2. Comparison: wait/notify vs. Condition Object Feature Object.wait/notify java.util.concurrent.Condition Association Every Java Object has one. Associated with a ReentrantLock. Capability Only one “wait set” per object. Multiple conditions per lock (e.g., notFull and notEmpty). Control Standard synchronized blocks. Precision control with signal() and await(). Analogy A single waiting room for a whole office. Multiple specific waiting rooms (e.g., “Radiology” vs “ER”). 3. The “Golden” Snippet: Multi-Condition Producer-Consumer Using Condition objects with ReentrantLock allows us to be very specific about which threads we wake up. ...