6

I need a simple example of use of the volatile keyword in Java, behaving inconsistently as a result of not using volatile.

The theory part of volatile usage is already clear to me.

informatik01
  • 15,174
  • 9
  • 67
  • 100
user1418683
  • 61
  • 1
  • 2

1 Answers1

13

First of all, there's no guaranteed way of exposing caching due to non-volatile variables. Your JVM might just be very kind to you all the time and effectively treat every variable as volatile.

That being said, there are a few ways to increase probability of having threads caching their own versions of a non-volatile variable. Here is a program that exposes the importance of volatile in most machines I've tested it on (adapted version from here):

class Test extends Thread {

    boolean keepRunning = true;

    public void run() {
        while (keepRunning) {
        }

        System.out.println("Thread terminated.");
    }

    public static void main(String[] args) throws InterruptedException {
        Test t = new Test();
        t.start();
        Thread.sleep(1000);
        t.keepRunning = false;
        System.out.println("keepRunning set to false.");
    }
}

This program will typically just output

keepRunning set to false.

and continue running. Making keepRunning volatile causes it to print

keepRunning set to false.
Thread terminated.

and terminate.

Community
  • 1
  • 1
aioobe
  • 383,660
  • 99
  • 774
  • 796
  • 2
    Funny, if you make the loop do something, the example will no longer work (e.g. `System.out.println(".");` inside `while(keepRunning)` – Miquel Jul 24 '12 at 08:54
  • it's because `System.out.println(...) is synchronized ` https://stackoverflow.com/questions/17748078/simplest-and-understandable-example-of-volatile-keyword-in-java – Santanu Sahoo May 26 '20 at 13:14