Java Reference
In-Depth Information
The problem with
UnsafeSequence
is that with some unlucky timing, two threads could
crement notation,
nextValue++
, may
appear
to be a single operation, but is in fact three
separate operations: read the value, add one to it, and write out the new value. Since opera-
tions in multiple threads may be arbitrarily interleaved by the runtime, it is possible for two
threads to read the value at the same time, both see the same value, and then both add one
to it. The result is that the same sequence number is returned from multiple calls in different
threads.
Diagrams like
Figure 1.1
depict possible interleavings of operations in different threads. In
these diagrams, time runs from left to right, and each line represents the activities of a differ-
show the danger of incorrectly assuming things will happen in a particular order.
UnsafeSequence
uses a nonstandard annotation:
@NotThreadSafe
. This is one of
several custom annotations used throughout this topic to document concurrency properties
of classes and class members. (Other class-level annotations used in this way are
thread safety are useful to multiple audiences. If a class is annotated with
@ThreadSafe
,
users can use it with confidence in a multithreaded environment, maintainers are put on no-
tice that it makes thread safety guarantees that must be preserved, and software analysis tools
can identify possible coding errors.
UnsafeSequence
illustrates a common concurrency hazard called a
race condition
.
Whether or not
nextValue
returns a unique value when called from multiple threads, as
required by its specification, depends on how the runtime interleaves the operations—which
is not a desirable state of affairs.