Java Reference
In-Depth Information
by any processor. This happy, if unrealistic, model is called sequential consistency . Software
developers often mistakenly assume sequential consistency, but no modern multiprocessor
offers sequential consistency and the JMM does not either. The classic sequential computing
model, the von Neumann model, is only a vague approximation of how modern multipro-
cessors behave.
The bottom line is that modern shared-memory multiprocessors (and compilers) can do some
surprising things when data is shared across threads, unless you've told them not to through
the use of memory barriers. Fortunately, Java programs need not specify the placement of
memory barriers; they need only identify when shared state is being accessed, through the
proper use of synchronization.
16.1.2. Reordering
In describing race conditions and atomicity failures in Chapter 2 , we used interaction dia-
grams depicting “unlucky timing” where the scheduler interleaved operations so as to cause
incorrect results in insufficiently synchronized programs. To make matters worse, the JMM
can permit actions to appear to execute in different orders from the perspective of different
threads, making reasoning about ordering in the absence of synchronization even more com-
plicated. The various reasons why operations might be delayed or appear to execute out of
order can all be grouped into the general category of reordering .
PossibleReordering in Listing 16.1 illustrates how difficult it is to reason about the
behavior of even the simplest concurrent programs unless they are correctly synchronized. It
is fairly easy to imagine how PossibleReordering could print (1, 0), or (0, 1), or (1, 1):
thread A could run to completion before B starts, B could run to completion before A starts,
or their actions could be interleaved. But, strangely, PossibleReordering can also print
(0, 0)! The actions in each thread have no dataflow dependence on each other, and accord-
ingly can be executed out of order. (Even if they are executed in order, the timing by which
caches are flushed to main memory can make it appear, from the perspective of B , that the
assignments in A occurred in the opposite order.) Figure 16.1 shows a possible interleaving
with reordering that results in printing (0, 0).
Search WWH ::




Custom Search