JAVA-BASED REAL-TIME PROGRAMMING
JAVA-BASED REAL-TIME PROGRAMMING
JAVA-BASED REAL-TIME PROGRAMMING
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
3.3. Objects providing mutual exclusion – Monitors<br />
(for example in unknown subclasses) can interfere. Therefore, a delay within<br />
a monitor should be implemented similar to:<br />
synchronized monitorSleep(long timeout) throws InterruptedException {<br />
long tf = System.currentTimeMillis ()+timeout;<br />
while ((timeout=tf-System.currentTimeMillis ())>0) wait(timeout);<br />
}<br />
Also note that if timeout milliseconds elapsed from the call of wait until the<br />
calling thread executes the instruction following wait, we cannot distinguish<br />
between if:<br />
1. The wait was called and timeout ms later we continued after a timeout.<br />
2. The wait was called and before the timeout time some other thread called<br />
notify, but due to scheduling more than timeout ms elapsed before the<br />
statement after wait was executed.<br />
3. Other threads were scheduled for execution right before wait was actually<br />
called, then during the wait some other thread called notify, but<br />
due to the initial delay more than timeout ms elapsed.<br />
Thus, even if it is only in case 1 that the runtime system issued a timeout, we<br />
can obtain waiting for that amount of time due to the (platform dependent)<br />
scheduling. In code this means, dt can be greater than timeout even if wait<br />
was completed due to a notification:<br />
long t0 = System.currentTimeMillis ();<br />
wait(timeout);<br />
long dt = System.currentTimeMillis()-t0;<br />
Is this a problem? Normally not; it does usually not matter if we were notified<br />
or not, it is the inferred delay that matters for the calling thread. Hence, if<br />
dt>timeout it is considered as a timeout. On the other hand, if the state of<br />
the monitor stated that our thread was waiting, and some other thread calling<br />
notifyAll determined that it issued the notification on time (before a timeout<br />
occurred) and subsequently acted according to that, the possible cases 2 and 3<br />
above may imply a need for some more monitor logic. That is, if it logically is<br />
not a timeout, only checking if dt>timeout after the previous code fragment<br />
is not sufficient; concurrency correctness may require some more monitor logic<br />
to cope with all possible interleavings, as always.<br />
Interrupted waiting<br />
When a thread that is blocked on wait (with or without timeout), or on sleep<br />
as described on page 51, the blocking is interrupted and an InterruptedException<br />
is thrown to the calling thread. The appropriate handling of such<br />
an interrupted wait is typically known/defined in the calling thread outside<br />
the monitor methods. Hence, it must propagate to the caller, so the obvious<br />
81