I'm curious what happens underneath when my thread gets to a synchronized block and blocks the monitor.
Does it actually call wait() implicitly on all other threads that try to use this monitor? Or the monitor has some specific flags that being changed?
Also, what happens when we get out of the synchronized block? Does it somehow call notify or notifyAll for current monitor?
I am really tangled up about this.
I think it is best to think in terms of underlying synchronization primitives: a java monitor is a mutex, a synchronized block is a region where the mutex is locked upon {
and unlocked upon }
and wait, notify and notifyAll are methods called on a condition variable associated with the mutex.
The important thing to remember is that the mutex can become unlocked within the synchronized block when wait()
is called since wait will unlock the mutex and block until notify or notifyAll is called.
Thus, multiple threads can still be blocked within a synchronized block despite the inference that this is not possible.
Update: Annotated code demonstrating this:
Object lock;
// ...
synchronized (lock) { // Underlying mutex is locked.
// ...
lock.wait(); // Unlocks mutex, blocks until notify, relocks mutex
// ...
} // Underlying mutex unlocked
Once lock.wait()
is called, other threads are free to enter the synchronized block. They too will block until either a lock.notify()
or lock.notifyAll()
wakes them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With