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. Multi-Threaded Programming<br />
class Buffer { // Inefficient!!<br />
synchronized void post(Object obj) {<br />
while (buff.size()>=maxSize) {<br />
wait();<br />
}<br />
buff.add(obj);<br />
notifyAll();<br />
}<br />
}<br />
synchronized Object fetch() {<br />
while (buff.isEmpty()) {<br />
wait();<br />
}<br />
return buff.remove();<br />
notifyAll();<br />
}<br />
class Buffer { // Well done.<br />
synchronized void post(Object obj) {<br />
while (buff.size()>=maxSize) {<br />
wait();<br />
}<br />
if (buff.isEmpty()) notifyAll();<br />
buff.add(obj);<br />
}<br />
}<br />
synchronized Object fetch() {<br />
while (buff.isEmpty()) {<br />
wait();<br />
}<br />
if (buff.size()>=maxSize) notifyAll();<br />
return buff.remove();<br />
}<br />
Figure 3.9: Two alternative implementations of the Buffer class. Declarations,<br />
initializations, and exception handling is omitted as in Figure 3.8.In the left<br />
version, all methods always call notifyAll (does not need to be last), possibly<br />
resulting in performance problems. In the version to the right, robustness and<br />
performance should be acceptable.<br />
wait(long timeout) The thread executing within the monitor temporarily<br />
leaves the monitor, waiting for a notification as normal. If notify is<br />
not called within timeout milliseconds, we give up waiting and return to<br />
the caller anyway. The timeout is minimum value; it can be longer as an<br />
implication of the actual scheduling of involved threads and the internal<br />
timer. A timeout equal to zero is equivalent to calling wait without any<br />
timeout argument. A negative timeout results in an IllegalArgumentException.<br />
wait(long timeout, int nanos) The same as previous wait but with the timeout<br />
time set to 1000000*timeout+nanos nanoseconds. Again, this is a<br />
minimum time that depends on the actual scheduling, if the resolution of<br />
time in our runtime system is high enough. However, with ms resolution<br />
or lower, the nanos are rounded to the nearest ms (!) which implies that<br />
the minimum timeout time can be up to 0.5 ms shorter than requested,<br />
but not shorter than the timeout since that value is rounded upwards if<br />
the clock resolution is lower than 1 ms.<br />
Note the difference between calling java.lang.Thread.sleep(delay) from within<br />
a monitor, and calling java.lang.Object.wait(delay). The former keeps the<br />
monitor locked during waiting/sleeping, whereas the latter lets other threads<br />
access the monitor during the delay time. It is, however, difficult to ensure that<br />
wait(delay) actually delays for at least delay ms since notify in other methods<br />
80 2012-08-29 16:05