JAVA-BASED REAL-TIME PROGRAMMING
JAVA-BASED REAL-TIME PROGRAMMING
JAVA-BASED REAL-TIME PROGRAMMING
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
class Account {<br />
int balance;<br />
Semaphore mutex = new MutexSem();<br />
void deposit(int amount) {<br />
mutex.take();<br />
balance += amount;<br />
mutex.give();<br />
}<br />
void withdraw(int amount) {<br />
mutex.take();<br />
balance -= amount;<br />
mutex.give();<br />
}<br />
}<br />
3.3. Objects providing mutual exclusion – Monitors<br />
class Account {<br />
int balance;<br />
synchronized void deposit(int amount) {<br />
balance += amount;<br />
}<br />
synchronized void withdraw(int amount) {<br />
balance -= amount;<br />
}<br />
}<br />
Figure 3.6: The bank account class to the left uses a semaphore for locking<br />
the object to accomplish mutual exclusion. By declaring the methods synchronized,<br />
as to the right, the same thing is achieved but in a simpler and<br />
more readable manner. In Java, there is an invisible lock in every object.<br />
is the topic of the next section, here we consider the case when concurrently<br />
executing threads actually need to call methods of the same object.<br />
Similar to when we use a MutexSem as a lock to provide exclusive access to<br />
an object, we need some kind of lock also when methods are synchronized. In<br />
Java, there is such a lock available in each object, even for the ordinary ones!<br />
The synchronized keyword tells the compiler to generate code that uses the<br />
lock. Thereby, the program gets more easy to read and write. For instance,<br />
consider the bank account in Figure 3.6.<br />
Synchronized blocks<br />
While the use of synchronized methods improves readability (compared to<br />
the use of semaphores), Java also provides a less (compared to proper use of<br />
monitors) structured alternative for locking an object; the synchronized block.<br />
Within the braces the object obj is locked for exclusive use:<br />
synchronized(obj) { /* Exclusive access to obj here.. */ }<br />
Of course, a synchronized block uses the same object lock as the synchronized<br />
methods of that object, thereby making the block and the methods mutually<br />
exclusive. A synchronized method is equivalent to a method with the<br />
outermost block<br />
{ synchronized(this) { /* Method body here. */ } }<br />
The benefit of language support<br />
Both synchronized methods and blocks are very convenient when returning<br />
from a method. Compare this with the use of semaphores which resembles<br />
the situation when the language/compiler does not support synchronization or<br />
67