Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mechanics of notify()

 
Jon Dornback
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dana Hanna
Ranch Hand
Posts: 227
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or does it stay in some sort of contending-limbo until the sync block exits?

Bingo
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic