Sobes.tech
Junior — Middle

What is the difference between a semaphore and a monitor in the context of thread synchronization mechanisms?

sobes.tech AI

Answer from AI

A semaphore and a monitor are thread synchronization mechanisms, but they differ in their working principles and level of abstraction.

  • Semaphore is a low-level primitive that manages a count of permits. A thread attempts to acquire a permit (acquire operation), and if no permits are available, the thread blocks. After completing its work, the thread releases the permit (release). Semaphores can be binary (value 0 or 1) or allow a arbitrary number of permits.

  • Monitor is a higher-level abstraction, typically implemented as an object with built-in locking and condition variables. In Java, any object can be a monitor, synchronized using the synchronized keyword. A monitor provides mutual exclusion and the ability for threads to wait and be notified via wait(), notify(), and notifyAll() methods.

Key differences:

  • A semaphore manages a count of permits, while a monitor provides exclusive access to a resource.
  • A monitor is integrated into the object-oriented model of Java, whereas a semaphore is a separate class from java.util.concurrent.
  • A monitor supports waiting and notification of threads, while a semaphore only manages permits.

Example of using a monitor in Java:

synchronized (sharedObject) {
    while (!condition) {
        sharedObject.wait();
    }
    // critical section
    sharedObject.notifyAll();
}

Semaphore example:

Semaphore semaphore = new Semaphore(3); // 3 permits
semaphore.acquire(); // acquire a permit
// work with resource
semaphore.release(); // release the permit