Typical use of volatile in Java

We mentioned on the previous page that a volatile variable is one whose value is always written to and read from "main memory". That means that different threads can access the variable.1.

1. Recall that without using volatile (or some other synchronization mechanism), then thread A doesn't know that thread B might access the variable. So thread A thinks it's fair game to just cache the value of the variable in a register or in its local memory, and we run into problems.

A typical example of a simple variable that is written to and read from different threads is a "stop request" flag allowing one thread to signal to another to finish:

public class StoppableTask extends Thread {
  private volatile boolean pleaseStop;

  public void run() {
    while (!pleaseStop) {
      // do some stuff...
    }
  }

  public void tellMeToStop() {
    pleaseStop = true;
  }
}

If the variable were not declared volatile (and without other synchronization), then it would be legal for the thread running the loop to cache the value of the variable at the start of the loop and never read it again. If you don't like infinite loops, this is undesirable.

Volatile, memory synchronization and Java 5

We mentioned earlier that the meaning of volatile was tightened up in Java 5, and this tightened definition of volatile has actually been in part what has allowed some of the new concurrency facilities of Java 5. On the next page we'll look in more detail at the definition of volatile in Java 5.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.