Java Reference
In-Depth Information
Listing 3.1. Sharing Variables without Synchronization.
Don't Do this
.
NoVisibility
could loop forever because the value of
ready
might never become vis-
ible to the reader thread. Even more strangely,
NoVisibility
could print zero because the
write to
ready
might be made visible to the reader thread
before
the write to
number
, a
phenomenon known as
reordering
. There is no guarantee that operations in one thread will
be performed in the order given by the program, as long as the reordering is not detectable
main thread writes first to
number
and then to
done
without synchronization, the reader
thread could see those writes happen in the opposite order—or not at all.
In the absence of synchronization, the compiler, processor, and runtime can do some down-
right weird things to the order in which operations appear to execute. Attempts to reason
about the order in which memory actions “must” happen in insufflciently synchronized mul-
tithreaded programs will almost certainly be incorrect.