#Monitor

A monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true. Monitors are designed to be used safely in concurrent environments.

A monitor consists of a mutex and condition variables.

WorkFlow

  1. Mutual Exclusion: only one thread calls and gets access to the monitor method at a time
  2. Condition Synchronization: Threads can wait on condition variables if they can’t proceed
  3. Signaling: Threads can signal or broadcast to wake up sleeping threads when conditions change
  4. Automatic Release: The lock is automatically released when a thread exits the monitor or waits on a condition

Examples:

class BoundedBuffer {
    private final int[] buffer = new int[100];
    private int count = 0, in = 0, out = 0;
    
    public synchronized void put(int value) {
        while (count == buffer.length) {
            wait();  // Buffer is full, wait
        }
        buffer[in] = value;
        in = (in + 1) % buffer.length;
        count++;
        notify();  // Wake up consumer if it was waiting
    }
    
    public synchronized int get() {
        while (count == 0) {
            wait();  // Buffer is empty, wait
        }
        int value = buffer[out];
        out = (out + 1) % buffer.length;
        count--;
        notify();  // Wake up producer if it was waiting
        return value;
    }
}