I'm probably over-thinking this, but am hoping someone can shed some light on how this works. The notify() method must be called from within a sync block (because the monitor for that object must be owned by the calling thread). I'm ok with how the wait/notify process works, but am confused on this point: if notify() is called from within a sync block, how does another thread gain access to the locked object?
usually the call to notify is the last statement in a sync block, like the one above. I assume in this scenario that the sync block exits and then another thread is notified and starts to run. but what happens if notify is called before the end of the block?
in the above snippet, what happens? the API for notify does not specify that notify() releases the lock. does that mean that a thread wakes up, tries to get the lock, but since the current thread is still in the sync block the contending thread gives up and goes back to waiting? or does it stay in some sort of contending-limbo until the sync block exits? i think what this probably comes down to is when does the notify actually happen? right at the time the call to notify() is made? or does the JVM hold off notifying a thread until the sync block exits? sorry for the thousand question marks - it's just one of those finer points that i probably need not worry about but it's bugging me. -Jon
use the [CODE] tags - it makes it much easier for people to help you.
Joined: Jan 30, 2000
If notify() is called and then there's still more code to execute before you release the lock, the notified thread will have to wait until you release it. The thread is no longer wait()ing, it's moved to "trying to acquire a lock" mode - but it can't acquire the lock until the notifying thread releases it. So you're basically wasting a bit of time if you call notify() or notifyAll() anywhere other than (a) as close as possible to the end of the synchronized block, or (b) immediately before a wait() (in the same thread that did the notify()) which would have the effect of releasing the monitor.
"I'm not back." - Bill Harding, Twister
Joined: Feb 28, 2003
or does it stay in some sort of contending-limbo until the sync block exits?