Sobes.tech
Junior — Middle

Can you explain what is meant by 'monitor' in programming?

sobes.tech AI

Answer from AI

In programming, the term "monitor" usually refers to a synchronization mechanism that ensures mutual exclusion when accessing shared resources. It is an object that contains blocks of code, which can only be accessed by one thread at a time.

In Java, any object can be a monitor, as every object has an intrinsic monitor used with the synchronized keyword. When a thread enters a synchronized block or method, it acquires the object's monitor, and other threads attempting to enter the same block will wait until the monitor is released.

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 are synchronized, meaning the monitor of the Counter object guarantees that only one thread can execute these methods at a time, preventing race conditions.