Java - Thread and Volatile Variables

Introduction

A thread does not cache the value of a volatile variable in its working memory.

Using a volatile variable shared among threads is useful in a multi-threaded environment. It is faster and cheaper than using a synchronized block.

You can declare only a class member variable (instance or static fields) as volatile.

You cannot declare a volatile variable final because the volatile variables change.

The following code demonstrates the use of a volatile variable in multi-threaded environment.

Since the keepRunning variable is declared volatile, the JVM will read its value from the main memory.

public class Main extends Thread {
  private volatile boolean keepRunning = true;

  public void run() {
    System.out.println("Thread started...");

    // keepRunning is volatile. So, for every read, the thread reads its
    // latest value from the main memory
    while (keepRunning) {
      try {
        System.out.println("Going to sleep ...");
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("Thread stopped...");
  }

  public void stopThread() {
    this.keepRunning = false;
  }

  public static void main(String[] args) {
    // Create the thread
    Main vv = new Main();

    // Start the thread
    vv.start();
    // Let the main thread sleep for 3 seconds
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    // Stop the thread
    System.out.println("Going to set the stop flag to true...");
    vv.stopThread();
  }
}