06.08.2013 Views

JAVA-BASED REAL-TIME PROGRAMMING

JAVA-BASED REAL-TIME PROGRAMMING

JAVA-BASED REAL-TIME PROGRAMMING

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.2. Resources and mutual exclusion – Semaphores<br />

MultistepSem Counting semaphore permitting increments and decrements that<br />

are greater than one. Useful when two (or more) successive calls of take<br />

needs to be done without risk for preemption in between.<br />

MutexSem A Semaphore with special support for mutual exclusion. First, the<br />

implementation may check that the thread calling give owns the lock<br />

(that is, has taken the MutexSem). Secondly, this type of semaphore is<br />

required to provide so called priority inheritance (see Chapter 4) as a<br />

mean to obtain bounded response times for high priority threads when<br />

a low-priority thread is preempted and then starved when in a critical<br />

section.<br />

In principle, not considering real-time requirements and assuming correct programming,<br />

the MultistepSem could be used in all cases (or the CountingSem<br />

in almost all cases), but providing and using suitable abstractions is valuable<br />

in software development. Proposed usage:<br />

• Declare semaphore attributes and arguments to be of type Semaphore,<br />

except when the code is tailored to a specific type of semaphore.<br />

• In normal cases, instantiate a MutexSem for mutual exclusion and a<br />

CountingSem for signaling.<br />

• In special cases, use the BinarySem for signaling when ’catching up’ is<br />

not desired or for simplified resource reservation, and use the MultistepSem<br />

for signaling multiple steps in an atomic manner or for atomic<br />

reservation of multiple resources.<br />

All Semaphore classes are declared final to permit optimal code and mapping<br />

to native semaphores when cross-compiling to small embedded systems.<br />

Errors and exceptions<br />

When a blocking semaphore operation is interrupted, it results in SemInterrupted<br />

being thrown. When a thread calls mutex.give (where mutex is an<br />

instance of MutexSem) without first having acquired it by calling take, a<br />

SemViolation is thrown. The caller is not expected to catch these, except for<br />

properly shut-down of the application, since continued execution most likely<br />

will violate resource allocation rules and result in concurrency faults. Therefore,<br />

SemInterrupted and SemViolation are subclasses of java.lang.Error.<br />

That also gives the benefit that calls do not have to be surrounded by trycatch.<br />

When there are reasons to catch them, for instance right before thread<br />

termination, that is of course possible.<br />

65

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

Saved successfully!

Ooh no, something went wrong!