Java Reference
In-Depth Information
work as desired we have to do something such that when currentValue
is written, that written value becomes the only value that the memory
model will allow to be read. To do that we have to synchronize the writes
and the reads of variables.
14.10.1. Synchronization Actions
Certain actions a thread performs are defined as synchronization ac-
tions, and the order in which these actions are executed is termed the
synchronization order of the programthe synchronization order is always
consistent with the program order. These synchronization actions syn-
chronize reads and writes of variables.
The most familiar synchronization action is the use of synchronized
methods and blocks to ensure exclusive access to shared variables. The
release of a monitor lock is said to synchronize with all subsequent ac-
quisitions and releases of that monitor lock. If all reads and writes to
a variable occur only when a specific monitor is held, then each read
of the variable is guaranteed by the memory model to return the value
that was most recently written to it.
There is a second synchronization mechanism that doesn't provide the
exclusive access of monitors, but that again ensures that each read of a
variable returns the most recently written valuethe use of volatile vari-
ables. Fields (but not array elements) can be declared with the volatile
modifier. A write to a volatile variable synchronizes with all subsequent
reads of that variable. If currentValue was declared as volatile then the
example code we showed would be correctly synchronized and the latest
value would always be displayed. The use of volatile variables is seldom
a replacement for the use of synchronized methods or statements on
its own, because they don't provide atomicity across different actions.
Rather, volatile variables are most often used for simple flags to indicate
something has occurred, or for writing lock-free algorithms that incor-
porate use of the atomic variables mentioned in Section 25.9.1 on page
733 .
 
Search WWH ::




Custom Search