The synchronization problem from
CP Mini Lab 2
is now to be solved using a Java monitors.
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.
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.
Now, turn the class Counter into a monitor by declaring the
methods incr and read as
synchronized (inserted after public.)
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.
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!