Knowledge Guide
HomeConcurrencyConcurrency Foundations

4. Condition Variables

To understand the importance of condition variables, let's examine a producer-consumer scenario.

Suppose we have two threads: one serving as a producer and the other as a consumer. The producer's function is to generate a value, while the consumer's is to utilize that value. The key requirement is for the consumer thread to wait until a value has been produced.

At first glance, this might seem easily achievable using a mutex. However, a deeper analysis reveals an inherent inefficiency in the correct solution: busy-waiting.

Here is an example of an inefficient implementation.

java
public class Solution {

  private static final Object mtx = new Object();
  private static int sharedNumber;
  private static boolean ready = false;

  private static void producer() {
    synchronized (mtx) {
      sharedNumber = 42; // Producing a number
      ready = true;
      System.out.println("Producer has produced the number: " + sharedNumber);
    }
  }

  private static void consumer() {
    // Busy waiting loop
    while (true) {
      synchronized (mtx) {
        if (ready) {
          System.out.println(
            "Consumer has consumed the number: " + sharedNumber
          );
          break;
        }
      }
      try {
        Thread.sleep(1); // Sleep for a short time
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        System.out.println("Thread was interrupted");
      }
    }
  }

  public static void main(String[] args) {
    Thread producerThread = new Thread(Solution::producer);
    Thread consumerThread = new Thread(Solution::consumer);

    producerThread.start();
    consumerThread.start();

    try {
      producerThread.join();
      consumerThread.join();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      System.out.println("Main thread was interrupted");
    }
  }
}

To address this inefficiency, we can utilize a condition variable. In following approach, the consumer thread waits on a specific condition, while the producer thread, upon completing its task, signals or notifies this condition. Importantly, when the consumer thread is awakened by this notification, it automatically acquires the mutex. This ensures both efficient waiting and safe access to shared resources

java
public class Solution {
    private static final Object mtx = new Object();
    private static int sharedNumber;
    private static boolean ready = false;

    public static void producer() {
        synchronized (mtx) {
            sharedNumber = 42; // Producing a number
            ready = true;
            System.out.println("Producer has produced the number: " + sharedNumber);
            mtx.notify(); // Notify the consumer
        }
    }

    public static void consumer() {
        synchronized (mtx) {
            while (!ready) {
                try {
                    mtx.wait(); // Wait until the number is ready
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("Consumer thread was interrupted.");
                }
            }
            System.out.println("Consumer has consumed the number: " + sharedNumber);
        }
    }

    public static void main(String[] args) {
        Thread producerThread = new Thread(Solution::producer);
        Thread consumerThread = new Thread(Solution::consumer);

        producerThread.start();
        consumerThread.start();

        try {
            producerThread.join();
            consumerThread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("Main thread was interrupted.");
        }
    }
}

Here's a summary of the key components of this demonstration.

Shared Resource: The resource shared between the producer and consumer is an integer named sharedNumber. The producer thread modifies this number, and the consumer thread reads it.

Synchronization Mechanisms

Producer's Role

Consumer's Role

Synchronization and Communication

Demonstration of Condition Variables (or Equivalents)

🤖 Don't fully get this? Learn it with Claude

Stuck on 4. Condition Variables? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **4. Condition Variables** (Concurrency) and want to truly understand it. Explain 4. Condition Variables from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **4. Condition Variables** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **4. Condition Variables** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **4. Condition Variables** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes