11
Concurrency and interferences
The program ThreadInterferenceTest starts two Threads in parallel. The first, the Maker, increments a variable 1000000 times. The second, the Taker, decrements the same variable 1000000 times too. At the end, the program displays the value of the variable.
- public class ThreadInterferenceTest {
- static final private int NCALLS = 1000000;
- private int counter = 0;
- private Thread maker, taker;
- public ThreadInterferenceTest() {
- maker = new Thread(new Maker());
- taker = new Thread(new Taker());
- }
- public int getCounter() {
- return counter;
- }
- // MUST be synchonized
- public void inc() {
- counter++;
- }
- // MUST be synchonized
- public void dec() {
- counter--;
- }
- public void go() {
- maker.start();
- taker.start();
- try {
- maker.join();
- taker.join();
- }
- catch (InterruptedException e) {
- }
- }
- private class Maker implements Runnable {
- public void run() {
- for (int i = 0; i < NCALLS; i++)
- inc();
- }
- }
- private class Taker implements Runnable {
- public void run() {
- for (int i = 0; i < NCALLS; i++)
- dec();
- }
- }
- public static void main(String args[]) {
- ThreadInterferenceTest test = new ThreadInterferenceTest();
- test.go();
- System.out.println(test.getCounter());
- }
- }
$ javac ThreadInterferenceTest.java
$ java ThreadInterferenceTest
-92387
$ java ThreadInterferenceTest
-784617
Instead of obtaining the expected value, 0, the counter displays a random value. NOTE: If you get 0, run the program again. If necessary, increase the number of calls by changing the value of the constant NCALLS
.
Add the keyword synchronized
before the data type returned by inc
and dec
, between public
and void
, to ask Java to make sure that the execution of these methods is never interrupted.
- public synchronized void inc() {
- public synchronized void dec() {
$ javac ThreadInterferenceTest.java
$ java ThreadInterferenceTest
0
Comments