Java Reference
In-Depth Information
Locking is not just about mutual exclusion; it is also about memory visibility. To ensure that
all threads see the most up-to-date values of shared mutable variables, the reading and writ-
ing threads must synchronize on a common lock.
3.1.4. Volatile Variables
The Java language also provides an alternative, weaker form of synchronization, volatile
variables , to ensure that updates to a variable are propagated predictably to other threads.
When a field is declared volatile , the compiler and runtime are put on notice that this
variable is shared and that operations on it should not be reordered with other memory oper-
ations. Volatile variables are not cached in registers or in caches where they are hidden from
other processors, so a read of a volatile variable always returns the most recent write by any
thread.
A good way to think about volatile variables is to imagine that they behave roughly like the
SynchronizedInteger class in Listing 3.3 , replacing reads and writes of the volatile
variable with calls to get and set . [4] Yet accessing a volatile variable performs no locking
and so cannot cause the executing thread to block, making volatile variables a lighter-weight
synchronization mechanism than synchronized . [5]
The visibility effects of volatile variables extend beyond the value of the volatile variable it-
self. When thread A writes to a volatile variable and subsequently thread B reads that same
variable, the values of all variables that were visible to A prior to writing to the volatile vari-
able become visible to B after reading the volatile variable. So from a memory visibility per-
spective, writing a volatile variable is like exiting a synchronized block and reading a
volatile variable is like entering a synchronized block. However, we do not recommend
relying too heavily on volatile variables for visibility; code that relies on volatile variables
for visibility of arbitrary state is more fragile and harder to understand than code that uses
locking.
Use volatile variables only when they simplify implementing and verifying your syn-
chronization policy; avoid using volatile variables when veryfing correctness would re-
quire subtle reasoning about visibility. Good uses of volatile variables include ensuring
the visibility of their own state, that of the object they refer to, or indicating that an important
lifecycle event (such as initialization or shutdown) has occurred.
Search WWH ::




Custom Search