02158  Concurrent Programming - CP Mini Lab 4: Simple Java Monitor
Technical University of Denmark DTU
02158 Concurrent Programming        Fall 2024
CP Mini Lab 4: Simple Java Monitor
Home Plan Material  

Purpose

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

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 monitor.

  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.

  3. 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?)

  4. Now, turn the class Counter into a monitor by declaring the methods incr and read as synchronized (inserted after public.)
  5. Run the program again and find:
  6. 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.

Enjoy!

Hans Henrik Løvengreen, Oct 24, 2024

Answers:

  1. 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.
  2. 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.