Java Reference
In-Depth Information
For example, in the following (broken) code fragment, assume that this.done is a
non- volatile boolean field:
while (!this.done)
Thread.sleep(1000);
The compiler is free to read the field this.done just once, and reuse the cached value
in each execution of the loop. This would mean that the loop would never terminate,
even if another thread changed the value of this.done .
17.4. Memory Model
A memory model describes, given a program and an execution trace of that program,
whether the execution trace is a legal execution of the program. The Java programming
language memory model works by examining each read in an execution trace and checking
that the write observed by that read is valid according to certain rules.
The memory model describes possible behaviors of a program. An implementation is free
to produce any code it likes, as long as all resulting executions of a program produce a res-
ult that can be predicted by the memory model.
This provides a great deal of freedom for the implementor to perform a myriad of
code transformations, including the reordering of actions and removal of unnecessary
synchronization.
Example 17.4-1. Incorrectly Synchronized Programs May Exhibit Surprising Be-
havior
The semantics of the Java programming language allow compilers and micropro-
cessors to perform optimizations that can interact with incorrectly synchronized code
in ways that can produce behaviors that seem paradoxical. Here are some examples of
how incorrectly synchronized programs may exhibit surprising behaviors.
Consider, for example, the example program traces shown in Table 17.1 . This pro-
gram uses local variables r1 and r2 and shared variables A and B . Initially, A == B == 0 .
Table 17.1. Surprising results caused by statement reordering - original code
Search WWH ::




Custom Search