1

I have created a small program to understand Java Volatile keyword:

public class MultiThreadedCounter implements Runnable {

    private volatile int counter = 0;

    public void run() {

        increment();
        decrement();

    }

    private void decrement() {
        counter = counter - 5;
        System.out.println("dec = " + counter);
    }

    private void increment() {
        counter = counter + 5;
        System.out.println("inc = " + counter);
    }

    public static void main(String[] args) throws InterruptedException {
        MultiThreadedCounter m = new MultiThreadedCounter();
        Thread[] t = new Thread[100];
        int count = 0;
        while (true) {
            if (count >= 100) {
                break;
            }
            Thread t1 = new Thread(m);
            t[count] = t1;
            count++;
        }

        for (int i = 0; i < t.length; i++) {
            t[i].start();
        }
    }

}

Now in this program, I am seeing different set of results when I run the program multiple times.

Then I tried removing the volatile keyword for counter variable and observed similar results. i.e I am seeing different results when I run the program many times.

How Volatile helps in this program? When we need to use this keyword, I have gone through some material ans SO posts but I am not getting clear picture of the usage of this keyword.

learner
  • 6,062
  • 14
  • 79
  • 139
  • 1
    Of course you see different results... that's the essence of concurrent programming. You don't get to control the exact order of operations performed by multiple threads. Plus, your `inc` and `dec` methods are not atomic. – Marko Topolnik Jul 14 '15 at 21:41
  • The meaning of "volatile" is exactly defined in the Java Language Specification. – Thorbjørn Ravn Andersen Jul 14 '15 at 21:42
  • @MarkoTopolnik, Then how can I see the importance of volatile keyword. It says a single copy of the variable in main memory which is used by each thread before read/write operations. Can you please suggest some good example on how can test this scenario. As per my program I thought it should work and give consistent results. – learner Jul 14 '15 at 21:56
  • One good example: thread 1 runs a loop `while (runningFlag) {}`, thread 2 runs `Thread.sleep(3000); runningFlag = false;`. Thread 1 usually never stops as it never observes the update on `runningFlag`. – Marko Topolnik Jul 14 '15 at 22:02

0 Answers0