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. Multi-Threaded Programming<br />

concurrency, like in C/C++. Returning a value from a monitor method often<br />

requires the return value to be declared as an additional local variable, called<br />

ans in the following implementation of the class Account, not permitting the<br />

account to be overdrawn:<br />

1 class Account {<br />

2 int balance;<br />

3 Semaphore mutex = new MutexSem();<br />

4<br />

5 void deposit(int amount) { // As in implemented above.... }<br />

6<br />

7 int withdraw(int amount) {<br />

8 int ans = 0;<br />

9 mutex.take();<br />

10 if (amount > balance) {<br />

11 ans = amount - balance;<br />

12 balance = 0;<br />

13 } else {<br />

14 balance -= amount;<br />

15 }<br />

16 mutex.give();<br />

17 return ans;<br />

18 }<br />

19 }<br />

Based on this code, consider the following:<br />

• Having the local variable ans initialized and returned no longer makes<br />

the semaphore operations that clear as a scope for the critical section.<br />

• Line 8 and 9 could be swapped, technically, but what would happen if<br />

we swap lines 16 and 17?<br />

• If the introduced if-statement would be inserted in a larger method,<br />

there is the risk that lines 10 to 15 would have been implemented as<br />

int withdraw(int amount) {<br />

mutex.take();<br />

if (amount > balance) {<br />

balance = 0;<br />

return amount - balance; // Bug one.<br />

} else {<br />

balance -= amount;<br />

return 0; // Bug two.<br />

}<br />

mutex.give();<br />

}<br />

and the resource would have been locked forever after the first call.<br />

That would be an easy to find bug, but what if the return from inside<br />

the method (between take and give) only occurs in a very special case<br />

as evaluated in a more complex if statement? Deadlock in the shipped<br />

product after a few weeks at the customer site?<br />

• If the ans variable would be declared as an object attribute, like the<br />

balance attribute, we have a concurrency error. Mutual exclusion between<br />

deposit and withdraw still works (since ans is used only by the<br />

68 2012-08-29 16:05

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

Saved successfully!

Ooh no, something went wrong!