02158  Concurrent Programming - Mini Lab 2: Shared variables in Java
Technical University of Denmark DTU
02158 Concurrent Programming        Fall 2024
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 4] description of threads in Java.

Instructions

  1. Fetch the program Counting.java which is a small Java program with two concurrent threads that each 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:

    Explain the varying results.

  3. Lastly, 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 becomes small, the result may seem to become stable (and correct). Why?

Enjoy!

Hans Henrik Løvengreen, Sep 11, 2024