🧠 What Is a Monitor in Java?
A monitor is a synchronization construct that allows threads to have mutually exclusive access to critical sections of code or data.
In Java, every object has an implicit monitor — yes, even a new Object() has one!
🔐 Monitor = Mutual Exclusion + Wait/Notify Mechanism
A Java monitor does two key things:
- Mutual exclusion — Only one thread at a time can hold the monitor and execute a synchronized block/method.
- Coordination — Threads can use
wait(),notify(),notifyAll()to coordinate execution while holding the monitor.
🔄 What Acquires a Monitor?
- Synchronized instance method → locks the current object’s monitor (
this) - Synchronized static method → locks the class’s
.classmonitor - Synchronized block → locks the monitor of the provided object
🔍 Example: Object as a Monitor
class Counter {
private int count = 0;
public synchronized void increment() {
count++; // only one thread can do this at a time
}
}
Here:
- The method is
synchronized - The monitor of
thisobject (the instance ofCounter) is used - If Thread A is inside
increment(), Thread B must wait
Equivalent Using a Synchronized Block:
class Counter {
private int count = 0;
public void increment() {
synchronized (this) {
count++;
}
}
}
Same monitor — this
🛏 Coordination Example (Wait/Notify)
class MonitorExample {
private boolean ready = false;
public synchronized void waitForSignal() throws InterruptedException {
while (!ready) {
wait(); // releases monitor and waits
}
System.out.println("Got the signal!");
}
public synchronized void signal() {
ready = true;
notify(); // wakes up a waiting thread (if any)
}
}
Here:
wait()releases the monitor and pauses the threadnotify()signals a waiting thread to resume- Both can only be called while holding the monitor
🧠 Key Takeaways
| Concept | Meaning |
|---|---|
| Monitor | A per-object lock that enables mutual exclusion |
| Held by | A thread that enters a synchronized block/method |
| Wait() | Thread gives up monitor and goes into waiting state |
| Notify() | Wakes up one waiting thread (doesn’t release monitor) |
| Reentrant | Java monitors are reentrant — same thread can re-enter |
🔁 Monitors Are Hidden, but Real
Java doesn’t expose monitors directly — but under the hood:
synchronizedmaps to monitorenter/monitorexit bytecode- JVM handles it via OS-level locks
🔧 Summary
A monitor in Java is an object-level synchronization mechanism that ensures:
- Only one thread can execute synchronized code at a time
- Threads can wait and notify each other while synchronized