02152  Concurrent Systems - CP Mini Lab 4: Simple Java Monitor
Technical University of Denmark DTU
02152 Concurrent Systems        Fall 2008
CP Mini Lab 4: Simple Java Monitor
Home Plan Material  

Purpose

To se how shared variables can be protected by a simple Java monitor.

Prerequisites

Read about Java monitors in [Andrews 5.4] or [Sync 5].

Instructions

The synchronization problem from CP Mini Lab 2 is now to be solved using a Java monitors.

  1. Fetch the program MonitorCounting.java. This program is similar to that of CP mini lab 2 and 3, but the shared variable has been encapsulated within a class Counter.
  2. Compile and run the program and see once again that the incrementation fails.

    [But perhaps not as much as in mini lab 2 and 3 (why not?).]

    If you don't get varying results, you should use the class VIP as decribed in Mini Lab 2.

  3. Now, turn the class Counter into a monitor by declaring the methods incr and read as synchronized (inserted after public.)
  4. Run the program again and find:

Enjoy!

Hans Henrik Løvengreen, Sep 26, 2008

Answers:

  1. The incrementation fails whenever the execution of a thread is interrupted between reading and writing of x. In that case, the amount of "counting work" done by the other thread during its time slot is lost. In this lab, the probability of being interrupted is diminished since a procedure call is now to be done for each iteration of the loop. This, however, is outbalanced by the the whole process taking longer time. Thus, the number of critical interrupts is roughly the same as in mini lab 2 and 3. The amount of counting done by the other process within a time slot is less though and therefore the effect of a critical interrupt is smaller. In total, less incrementations are lost.
  2. As in the semaphore solution (mini lab 3), the program runs much slower because the monitor has to be entered for each call of incr. The use of critical regions is not for free!