💡 First: A Monitor in Java = A Mutex + Condition Variable
Java’s monitor is not just a lock — it’s a synchronization mechanism that includes:
- a mutex (for mutual exclusion)
- zero or more condition queues (for waiting/notification:
wait()
,notify()
)
🧵 Let’s Translate Java to Low-Level Terms
Java Code:
synchronized (obj) {
// critical section
}
Under the Hood (conceptually):
lock(obj->mutex); // monitorenter
// critical section
unlock(obj->mutex); // monitorexit
monitorenter
is like pthread_mutex_lock()
monitorexit
is like pthread_mutex_unlock()
Java uses reentrant mutexes, so the same thread can lock multiple times without deadlocking.
🔐 Key Concepts in Terms of Mutex
Java Concept | C / OS-Level Equivalent |
---|---|
synchronized(obj) | pthread_mutex_lock(&obj->mutex) |
monitorenter | Acquire mutex |
monitorexit | Release mutex |
wait() | pthread_cond_wait() (releases mutex, waits) |
notify() | pthread_cond_signal() |
notifyAll() | pthread_cond_broadcast() |
📦 How Scoped Synchronization Works (Step by Step)
public void doSomething() {
System.out.println("Before sync");
synchronized(this) {
System.out.println("In critical section");
}
System.out.println("After sync");
}
In terms of mutex:
Before sync
is unsynchronized codesynchronized(this)
:- JVM calls
monitorenter
→ acquires the mutex onthis
- Only one thread can pass this point at a time
- JVM calls
- Critical section runs
- Exiting block →
monitorexit
→ releases the mutex After sync
is again unsynchronized
So even though we’re locking on the object, we’re only holding the mutex for the duration of the block.
🛠 Real Mutex Behavior
Imagine 3 threads:
Thread-1: synchronized(obj) { ... }
Thread-2: synchronized(obj) { ... }
Thread-3: synchronized(obj) { ... }
This happens:
- Thread-1 acquires
obj
‘s mutex - Thread-2 and Thread-3 block (they spin or sleep waiting)
- When Thread-1 exits the block, mutex is released
- One of the others (e.g., Thread-2) wakes up and acquires the mutex
- Repeat
➡️ This is classic mutex behavior, just hidden inside the JVM.
🔁 Visual Summary
+------------------+ +------------------+
| Java Object | | Java Monitor |
|------------------| |------------------|
| Fields, etc. | <---> | Mutex (lock) |
| | | Condition(s) |
+------------------+ +------------------+
synchronized(obj) → monitorenter(obj) → mutex.lock()
exit block → monitorexit(obj) → mutex.unlock()
✅ Final Word
Yes — Java’s monitor is a high-level abstraction of a reentrant mutex + condition variable.
So when you write synchronized(obj)
, you’re doing exactly what you’d do in C with pthreads:
pthread_mutex_lock(&obj->mutex);
// do work
pthread_mutex_unlock(&obj->mutex);
Java just hides that plumbing — and makes it object-based and type-safe.