0

consider the following code

public class VolatileTester {

    public static volatile int a = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                int d = 0;
                while (d++ < 10000) {
                    a++;
                }
            }
        };

        Thread t2 = new Thread() {
            @Override
            public void run() {
                int d = 0;
                while (d++ < 10000) {
                    a++;
                }
            }
        };

        Thread t3 = new Thread() {
            @Override
            public void run() {
                int d = 0;
                while (d++ < 10000) {
                    a++;
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println(a);
    }
}

here as the variable a is volatile so I am expecting that the output should be 30000 but while running I am getting and in-deterministic answer which I will get anyway if the variable is not volatile.

so how volatile works is still remain unclear to me. can somebody put some light that where I am mistaken

khelwood
  • 55,782
  • 14
  • 81
  • 108
Sunil Garg
  • 484
  • 5
  • 9

1 Answers1

3

Just because you perform a volatile read, the following increment and store are not in any way affected. Your threads may e.g. each read 17, increment that, and store an 18

Think of it as a sequence of commands:

  • volatile load of your variable (always up to date)
  • Increment of what was loaded (which may be out of data at this point)
  • Writing back your incremented value (which may be out of date)

You need even stronger guarantees for this case. Look, for example, at AtomicInteger

Norwæ
  • 1,575
  • 8
  • 18
  • how do u modify the current example only by using volatile keyword and without any external keyword to achieve a value as 30000. is it possible. the reason for this question that I am not able to fully understand the meaning of volatile keyword – Sunil Garg Jul 30 '19 at 08:18