6

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Vadym Sidorov
  • 85
  • 1
  • 8
  • 4
    Possible duplicate of [How does the synchronize functionnality work in java?](http://stackoverflow.com/questions/6584355/how-does-the-synchronize-functionnality-work-in-java) – Johnny Willer Sep 30 '15 at 17:13
  • 1
    `wait()` is not something that one thread can do to another. A thread can only block _itself_ by calling `o.wait()`. The operations that happen at the beginning and end of a `synchronized` block are not available within the Java language itself. They have to be implemented in the JVM, and in most cases, the JVM merely calls out to the operating system. – Solomon Slow Sep 30 '15 at 17:39
  • @jameslarge You're right. Also, when I asked a question I misunderstood the waiting process: I thought that **wait** is the same as the **blocked** state of a thread, when it waits for monitor to be released. In fact, it has it own **wait set** that handles all wait() and notify() calls. – Vadym Sidorov Oct 01 '15 at 10:59

1 Answers1

6

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.

fcdt
  • 2,371
  • 5
  • 14
  • 26
Andy
  • 1,663
  • 10
  • 17