Home  Synchronization and concurrency  wait/notify  final  volatile  synchronized keyword  Java threading  Deadlock (and avoiding it)  Java 5: ConcurrentHashMap  Atomic variables  Explicit locks  Queues  Semaphores  CountDownLatch  CyclicBarrier

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.

Article written by Neil Coffey (@BitterCoffey).

Software

 LetterMeister (word puzzle game for iPhone)
 Currency Quoter (currency converter/predictor)
 French Vocab Games for iPhone/iPad
 Vocabularium: create Spanish vocab podcasts


Java programming articles and tutorials on this site are written by Neil Coffey (@BitterCoffey). Suggestions are always welcome if you wish to suggest topics for Java tutorials or programming articles, or if you simply have a programming question that you would like to see answered on this site. Most topics will be considered. But in particular, the site aims to provide tutorials and information on topics that aren't well covered elsewhere, or on Java performance information that is poorly described or understood. Suggestions may be made via the Javamex blog (see the site's front page for details).
Copyright © Neil Coffey 2014. All rights reserved.