• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Implementing stack using wait and notify

 
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
 
Everybody! Do the Funky Monkey! Like this tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic