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


i'm curious happens underneath when thread gets synchronized block , blocks monitor.

does call wait() implicitly on other threads try use monitor? or monitor has specific flags being changed?

also, happens when out of synchronized block? somehow call notify or notifyall current monitor?

i tangled this.

i think best think in terms of underlying synchronization primitives: java monitor mutex, synchronized block region mutex locked upon { , unlocked upon } , wait, notify , notifyall methods called on condition variable associated mutex.

the important thing remember mutex can become unlocked within synchronized block when wait() called since wait unlock mutex , block until notify or notifyall called.

thus, multiple threads can still blocked within synchronized block despite inference not possible.

update: annotated code demonstrating this:

object lock; ... synchronized (lock) { // underlying mutex locked. ... lock.wait(); // unlocks mutex, blocks until notify, relocks mutex ... } // underlying mutex unlocked

once lock.wait() called, other threads free enter synchronized block. block until either lock.notify() or lock.notifyall() wakes them.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -