Java Reference
In-Depth Information
The Java programming language provides a second mechanism,
volatile
fields, that is more
convenient than locking for some purposes.
A field may be declared
volatile
, in which case the Java Memory Model ensures that all
threads see a consistent value for the variable (§
17.4
).
It is a compile-time error if a
final
variable is also declared
volatile
.
Example 8.3.1.4-1.
volatile
Fields
If, in the following example, one thread repeatedly calls the method
one
(but no more
than
Integer.MAX_VALUE
times in all), and another thread repeatedly calls the method
two
:
class Test {
static int i = 0, j = 0;
static void one() { i++; j++; }
static void two() {
System.out.println("i=" + i + " j=" + j);
}
}
then method
two
could occasionally print a value for
j
that is greater than the value of
i
, because the example includes no synchronization and, under the rules explained in
One way to prevent this out-or-order behavior would be to declare methods
one
and
class Test {
static int i = 0, j = 0;
static synchronized void one() { i++; j++; }
static synchronized void two() {
System.out.println("i=" + i + " j=" + j);
}
}
This prevents method
one
and method
two
from being executed concurrently, and fur-
thermore guarantees that the shared values of
i
and
j
are both updated before method
one
returns. Therefore method
two
never observes a value for
j
greater than that for
i
;
indeed, it always observes the same value for
i
and
j
.