Java Reference
In-Depth Information
Another approach would be to declare
i
and
j
to be
volatile
:
class Test {
static volatile int i = 0, j = 0;
static void one() { i++; j++; }
static void two() {
System.out.println("i=" + i + " j=" + j);
}
}
This allows method
one
and method
two
to be executed concurrently, but guarantees
that accesses to the shared values for
i
and
j
occur exactly as many times, and in ex-
actly the same order, as they appear to occur during execution of the program text by
each thread. Therefore, the shared value for
j
is never 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
.
See §
17.4
for more discussion and examples.
8.3.2. Initialization of Fields
If a field declarator contains a
variable initializer
, then it has the semantics of an assign-
• If the declarator is for a class variable (that is, a
static
field), then the variable ini-
tializer is evaluated and the assignment performed exactly once, when the class is
• If the declarator is for an instance variable (that is, a field that is not
static
), then the
variable initializer is evaluated and the assignment performed each time an in-
stance of the class is created (§
12.5
).
Example 8.3.2-1. Field Initialization
class Point {
int x = 1, y = 5;
}
class Test {
public static void main(String[] args) {