Java Reference
In-Depth Information
NoVisibility
is about as simple as a concurrent program can get—two threads and two
shared variables—and yet it is still all too easy to come to the wrong conclusions about what
it does or even whether it will terminate. Reasoning about insufficiently synchronized con-
current programs is prohibitively difficult.
This may all sound a little scary, and it should. Fortunately, there's an easy way to avoid
these complex issues:
always usethe propersynchronization whenever dataissharedacross
threads.
3.1.1. Stale Data
NoVisibility
demonstrated one of the ways that insufficiently synchronized programs
can cause surprising results:
stale data
. When the reader thread examines
ready
, it may see
an out-of-date value. Unless synchronization is used
every time a variable is accessed
, it is
possible to see a stale value for that variable. Worse, staleness is not all-or-nothing: a thread
can see an up-to-date value of one variable but a stale value of another variable that was writ-
ten first.
When food is stale, it is usually still edible—just less enjoyable. But stale data can be more
values can cause serious safety or liveness failures. In
NoVisibility
, stale values could
cause it to print the wrong value or prevent the program from terminating. Things can get
even more complicated with stale values of object references, such as the link pointers in a
linked list implementation.
Staledatacancauseseriousandconfusingfailuressuchasunex-
pected exceptions, corrupted data structures, inaccurate computations, and infinite loops.
from both
get
and
set
without synchronization. Among other hazards, it is susceptible to
stale values: if one thread calls
set
, other threads calling
get
may or may not see that up-
date.
We can make
MutableInteger
thread safe by synchronizing the getter and setter as
be sufficient: threads calling
get
would still be able to see stale values.
Listing 3.2. Non-thread-safe Mutable Integer Holder.