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

1

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.

Forebear answered 30/9, 2015 at 17:8 Comment(3)
Possible duplicate of How does the synchronize functionnality work in java?Volgograd
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.Handpick
@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.Forebear
A
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.

Asthenic answered 30/9, 2015 at 17:37 Comment(4)
by the words block until notify or notifyAll you meant that it gets into waiting set?Forebear
@JamesFord - I've added annotated code to the answer demonstrating this.Asthenic
@JamesFord - Feel free to accept the answer if it's acceptable to you.Asthenic
actually I got stuck with a bit different that you explained, but the answer is valid, thanks.Forebear

© 2022 - 2024 — McMap. All rights reserved.