06.08.2013 Views

JAVA-BASED REAL-TIME PROGRAMMING

JAVA-BASED REAL-TIME PROGRAMMING

JAVA-BASED REAL-TIME PROGRAMMING

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.3. Objects providing mutual exclusion – Monitors<br />

synchronized(.){<br />

Exclusive area<br />

Thread with exclusive<br />

access to monitor data<br />

}<br />

wait<br />

Scheduling<br />

notify<br />

Thread just left monitor<br />

Thread about<br />

to enter<br />

waiting for exclusive access<br />

Monitor queue<br />

awaiting fulfilled condition<br />

Condition queue<br />

Figure 3.7: The monitor concept, including the wait-notify mechanism as a<br />

back yard. The crosses are revolving doors, that is, the door turns in the<br />

direction of the bent arrow and threads can only pass in the direction shown<br />

by the straight arrow.<br />

notify to wake up one of the blocked threads. If the condition queue is<br />

empty, notify does nothing. It depends on the runtime system which of<br />

the blocked threads that are selected for notification, but here we assume<br />

the normal case that it is the first in queue thread, which in turn<br />

is the one with the highest priority.<br />

After the thread is notified and ready for execution, it has to compete<br />

for CPU time with all other threads to advance its execution point at all.<br />

When execution advances, the thread also has to compete (again!) with<br />

other threads for exclusive access to the monitor, and if not successful it<br />

is blocked and placed in the monitor queue (in priority order we assume,<br />

even if not specified by Java).<br />

notifyAll() All the threads in the condition queue are notified, and thereby<br />

made ready for execution. They are then all subject to scheduling as<br />

explained for notify. Since scheduling is not part of the Java specification,<br />

and since knowing what threads that might be using the monitor<br />

requires global information, the reliable and portable way of notification<br />

is to always call notifyAll instead of notify; the use of notify is purely<br />

for optimization and performance tuning (to prevent excessive context<br />

switches that can be the case when many threads first are unblocked<br />

and then all but one calls wait again when the condition again is not<br />

fulfilled).<br />

75

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!