Sobes.tech
Senior

What is a monitor in Java?

sobes.tech AI

Answer from AI

In Java, a monitor is a synchronization mechanism that provides mutual exclusion (mutex) when accessing shared resources. Each object in Java is associated with a monitor, which is used with the synchronized keyword to lock and unlock.

When a thread enters a synchronized block or method, it acquires the monitor of the object, and other threads cannot enter that block until the monitor is released. This prevents race conditions and ensures correct operation with shared data.

Example:

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

Here, the increment and getCount methods use the monitor of the Counter object to synchronize access.

What is a monitor in Java? — Java - sobes.tech