Java Reference
In-Depth Information
Listing 3.4 illustrates a typical use of volatile variables: checking a status flag to determine
when to exit a loop. In this example, our anthropomorphized thread is trying to get to sleep by
the time-honored method of counting sheep. For this example to work, the asleep flag must
be volatile. Otherwise, the thread might not notice when asleep has been set by another
thread. [6] We could instead have used locking to ensure visibility of changes to asleep , but
that would have made the code more cumbersome.
Listing 3.4. Counting Sheep.
Volatile variables are convenient, but they have limitations. The most common use for volat-
ile variables is as a completion, interruption, or status flag, such as the asleep flag in List-
ing 3.4 . Volatile variables can be used for other kinds of state information, but more care
is required when attempting this. For example, the semantics of volatile are not strong
enough to make the increment operation ( count++ ) atomic, unless you can guarantee that
the variable is written only from a single thread. (Atomic variables do provide atomic read-
modify-write support and can often be used as “better volatile variables”; see Chapter 15 . )
Locking can guarantee both visibility and atomicity; volatile variables can only guarantee
visibility.
You can use volatile variables only when all the following criteria are met:
Writes to the variable do not depend on its current value, or you can ensure that only
a single thread ever updates the value;
The variable does not participate in invariants with other state variables; and
Locking is not required for any other reason while the variable is being accessed.
Search WWH ::




Custom Search