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?
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.
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.
"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
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.
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.