GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Implementing stack using wait and notify Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Implementing stack using wait and notify" Watch "Implementing stack using wait and notify" New topic
Author

Implementing stack using wait and notify

Naresh Chaurasia
Ranch Hand

Joined: May 18, 2005
Posts: 356
Consider following code



When the wait is called at (1), does the thread give up the lock immediately and the execution of push begins or the lock is given up when the synchronized method pop() comes to end.


SCJP 1.4, SCWCD1.4, OCA(1Z0-007)
Trivikram Kamat
Ranch Hand

Joined: Sep 26, 2010
Posts: 155
Naresh Chaurasia wrote:
When the wait is called at (1), does the thread give up the lock immediately and the execution of push begins or the lock is given up when the synchronized method pop() comes to end.


The lock (on which method is synchronized) is relinquished as soon as you call wait()
The execution of push() will begin only when it acquires the lock. Remember that the lock is relinquished by pop() by calling wait() doesn't mean it'll be acquired by push(). It may be acquired by some other method also - say by some other method pop() or method push() being run in different thread.

In this case when notify() is invoked in method push(), it'll wake up single thread which may be running pop() - depending on thread policies implemented by JVM (in case many threads are waiting for that lock)
Note that the object lock is not relinquished when the notifying thread invokes the notify() method. The notifying thread relinquishes the lock
at its own discretion, only then awakened thread can acquire the lock.

OCPJP6
 
 
subject: Implementing stack using wait and notify