• Post Reply Bookmark Topic Watch Topic
  • New Topic

Printing numbers in sequence in different threads

 
Tushar Goel
Ranch Hand
Posts: 931
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question is relates to the another question asked here. I have used Semaphore to achieve the same.
I dont want to hi jack that posts thats why i am here.





I have confusion for line 22 and 24 in PrintNumbers class. Line 22 seems understande if i dont sleep enough time then lock re-acquires but not sure for line 24. Any idea?
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line 24 is covering the possibility that the thread (sleep or tryAcquire) is woken by a rare event "a spurious wakeup" i.e. the thread aquire or sleep did not take 500ms before failing.

https://en.wikipedia.org/wiki/Spurious_wakeup

Also discussed here ... http://www.coderanch.com/t/234023/threads/java/spurious-wakeup

An example use case if in the OS for some reason it needed to adjust the clock it might use this so you were woke up and could adjust your algorithm i.e. you might be waiting 500ms because that's when your flight leaves in real time and this wakeup allows you to adjust for the fact your watch was effectively wrong when you slept. In reality this may never occur with your OS/VM and even if its possible you'd expect it to be very rare.

Normally I would expect the try/catch within the loop and I'm not sure why you need the Thread.Sleep as the acquire is timed.
 
Tushar Goel
Ranch Hand
Posts: 931
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chris. So to avoid this "a spurious wakeup", i should use some condition to satisfy instead of using while(true) in both the class. So if i do that then don't have
to instantiate semaphore again.
 
Tushar Goel
Ranch Hand
Posts: 931
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
something like this:



I am not sure what flag to use in below class. I have used several like to compare number of available permits, drain or queue length but nothing works.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!