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
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).]
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:
Increase the number of iterations (N) with a factor of 10 until the program takes several seconds to execute. Now
you are expected to get varying results.]
Explain the varying results.
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?