The synchronization problem from
CP Mini Lab 2
is now to be solved using a Java monitor.
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.
In class Counter try to declare the variable x
to be volatile [as any directly shared variable/field
should always be].
Observe, that the program still does not count correctly and now
runs somewhat slower. (why?)
Now, turn the class Counter into a monitor by declaring the
methods incr and read as
synchronized (inserted after public.)
Run the program again and find:
that the program runs even slower than before (why?).
but the counting is now correct :-)
Once turned into a monitor, the fields of this need not be declared
volatile any longer as the proper memory access
ordering is taken care of by
the synhronized declarations.
Remove the volatile attribute of x and find, that it has
little effect on the execution time.
By the volatile declaration, all accesses to x will be
properly ordered. This affects many of the processor optimizations
rendering the program slower. Also, the race condition persists as
the read and subsequent write of x are still not done atomically.
As the accesses to x are now done under mutual exclusion, the
increment becomes atomic, but the
concurrency is reduced leading to longer execution time.