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.3. Objects providing mutual exclusion – Monitors<br />
outside the monitor class, you better use a private lock object which is<br />
locked by a synchronized block in each monitor operation. A monitor<br />
then looks like:<br />
public class RobustMonitorExample {<br />
private Object lock = new Object();<br />
// More attributes are declared here ....<br />
}<br />
public void methodOne(int x) {<br />
synchronized(lock) {<br />
// Attributes are accessed here....<br />
}<br />
}<br />
This way, other objects cannot interfere with the synchronization. Again,<br />
the unfortunate Java design decision to support synchronized blocks but<br />
not synchronized classes with appropriate semantics causes extra trouble<br />
when developing reliable software. Still, the situation is better than<br />
in other major languages. Recall this item when reading about wait and<br />
notify below. Another example will be the non-native Java implementation<br />
of semaphores.<br />
3. Do not synchronize on public attributes. That is, if you (against the<br />
general guideline) synchronize on an attribute like the lock in the previous<br />
item, that attribute should be private or final. Otherwise, that<br />
object reference may change from one synchronization point to another,<br />
thereby removing the synchronization. Locking cannot be ensured if the<br />
look can replaced by anyone.<br />
4. Do not remove synchronization by subclassing (unless it is a final class<br />
and you really know what you are doing). If a base class declares a<br />
method as synchronized, the subclass should do so too. There is nothing<br />
in Java enforcing such a practice, and you might want to optimize<br />
methods in a subclass by omitting synchronized, but the risk for hardto-find<br />
concurrency errors normally is too high considering the interplay<br />
between monitor methods.<br />
5. If synchronization is needed between multiple monitors, such as interconnected<br />
buffers, they of course need an object in common to synchronize<br />
on. An alternative would be to merge the different monitors to form one<br />
monitor with all the functionality included, but suitable monitor classes<br />
may be available already; just the signaling and mutual exclusion between<br />
them need to be added. Using synchronized blocks to synchronize<br />
on some shared lock object (such as one of the monitors if that code has<br />
been prepared for it) is clearly preferable compared to rewriting the<br />
application.<br />
As mentioned in the last item, the need for synchronization between objects<br />
can be due to the need for signaling (which we earlier accomplished<br />
73