volatile keyword

Syntax

>>-+-----------+-+--------+-+-----------+-volatile-Type->
   +-public----+ '-static-' '-transient-'
   +-protected-+
   '-private---'

>-+-Identifier--------------+-+----------------------+-;-><
  |                 v-----' | '-=-+-Expression-------'
  '-ArrayIdentifier-+-[-]-+-'     '-ArrayInitializer-'

Description
The volatile modifier is used when you are working with multiple threads.

The Java language allows threads that access shared variables to keep private working copies of the variables; this allows a more efficient implementation of multiple threads. These working copies need be reconciled with the master copies in the shared main memory only at prescribed synchronization points, namely when objects are locked or unlocked. As a rule, to ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that, conventionally, enforces mutual exclusion for those shared variables.

Java provides a second mechanism that is more convenient for some purposes: a field may be declared volatile, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.

If a constant declaration in an interface includes the modifier volatile, a compilation error occurs.

If a final variable is also declared volatile, a compilation error occurs.

Example
The following example shows a use of the volatile keyword:

class Test {
    static volatile int i = 0; j = 0;

    static void one() { i++; j++; }

    static void two() {
        System.out.println("i=" + i + " j=" + j);
    }
}

The use of the volatile keyword allows method one and method two to be executed concurrently, but guarantees that accesses to the shared value for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text be each thread.  Therefore, method two never observes a value for j greater than that for i, because each update to i must be reflected in the shared value for i before the update to j occurs.  It is possible, however, that any given invocation of method two might observe a value for j that is much greater than the value observed for i, because method one might be executed many times between the moment when method two fetches the value of i and the moment when method two fetches the value of j.

The following is an example of a volatile variable:

static volatile int v = 0;

ngrelr.gif (548 bytes)
Syntax diagrams
Java types
final keyword
private keyword
protected keyword
public keyword
static keyword
transient keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.