Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly happens when thread enters a synchronized block / method in Java

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.

like image 522
Vadym Sidorov Avatar asked Sep 30 '15 17:09

Vadym Sidorov


1 Answers

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.

like image 124
Andy Avatar answered Oct 23 '22 05:10

Andy