Java Reference
In-Depth Information
Unfortunately,
UnsafeCountingFactorizer
is not thread-safe, even though it would
it is susceptible to
lost updates
. While the increment operation,
++count
, may look like a
single action because of its compact syntax, it is not
atomic
, which means that it does not
execute as a single, indivisible operation. Instead, it is a shorthand for a sequence of three
discrete operations: fetch the current value, add one to it, and write the new value back. This
is an example of a
read-modify-write
operation, in which the resulting state is derived from
the previous state.
Figure 1.1
on page
6
shows what can happen if two threads try to increment a counter sim-
ultaneously without synchronization. If the counter is initially 9, with some unlucky timing
each thread could read the value, see that it is 9, add one to it, and each set the counter to 10.
This is clearly not what is supposed to happen; an increment got lost along the way, and the
hit counter is now permanently off by one.
You might think that having a slightly inaccurate count of hits in a web-based service is an
acceptable loss of accuracy, and sometimes it is. But if the counter is being used to generate
sequences or unique object identifiers, returning the same value from multiple invocations
ence of unlucky timing is so important in concurrent programming that it has a name: a
race
condition
.