• 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

How to solve this wait() and notify() issue?

 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,

consider the following class



In the above code

1. is there any chance that wait() statement is getting executed in between the execution of call() method?
2. In the above code i experience the following problem
if isCompleted() returns true for the first time the notify() statement gets called before the execution of wait()which causes this thread to wait indefinitely. how to avoid this situation?

Regards,
Ajay.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

2. In the above code i experience the following problem
if isCompleted() returns true for the first time the notify() statement gets called before the execution of wait()which causes this thread to wait indefinitely. how to avoid this situation?



There are two rules that you should follow...

1. Never call wait() blindly. Always check to see if you should wait before calling wait. This check should be done within the synchronized block, due to race conditions.

2. Never assume that a return from wait() puts you in an okay state. Always check again to see if you should go back into a wait condition, when returning from wait.

Hence, you code should look like this...



Henry
 
Henry Wong
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One other issue... the wait() and notify() mechanism is for communication between multiple threads. If the thread that is calling notify(), is the same thread that is calling wait(), you can pretty much be assured that the notifications will not be recieved... as the thread that is supposed to be waiting is guarranteed *not* to be waiting when the notification is sent... :-)

Henry
 
reply
    Bookmark Topic Watch Topic
  • New Topic