02152  Concurrent Systems - CP Mini Lab 2: Shared variables in Java
Technical University of Denmark DTU
02152 Concurrent Systems        Fall 2008
CP Mini Lab 2: Shared variables in Java
Home Plan Material  

Purpose

To experience the race condition problem with shared variables in Java.

Prerequisites

See the note about processes and threads [Proc], section 4, for a description of threads in Java.

Instructions

  1. Fetch the program Counting.java that is a small Java program with two concurrent threads that increments a variable x a large number of times.

     
    [The volatile-modifier on a variable declaration ensures that any change of the variable is actually written to the variable (and not just held in a register for optimization).]

  2. Run the program a couple of times and see whether the result is always the same.

    If you get the same (correct) result every time, try the following:

  3. As a last point, try to reduce the number of iterations with a factor of 10 at a time and run the program several times. When the number of iterations become small, the result may become stable (and correct). Why?

     
    Note that on a multiprocessor (such as in the G-databar or a dual-core machine), you may have to go very low and even then, the result may not become stable. Explain this.

Enjoy!


In case you experience that you cannot get varying results in the second step, you may try to enforce preemption by:

Hans Henrik Løvengreen, Sep 5, 2008