Java Reference
In-Depth Information
1.3. Risks of Threads
Java's built-in support for threads is a double-edged sword. While it simplifies the devel-
opment of concurrent applications by providing language and library support and a formal
cross-platform memory model (it is this formal cross-platform memory model thatmakes pos-
sible the development of write-once, run-anywhere concurrent applications in Java), it also
raises the bar for developers because more programs will use threads. When threads were
more esoteric, concurrency was an “advanced” topic; now, mainstream developers must be
aware of thread-safety issues.
1.3.1. Safety Hazards
Thread safety can be unexpectedly subtle because, in the absence of sufficient synchroniza-
tion, the ordering of operations in multiple threads is unpredictable and sometimes surprising.
UnsafeSequence in Listing 1.1 , which is supposed to generate a sequence of unique in-
teger values, offers a simple illustration of how the interleaving of actions in multiple threads
can lead to undesirable results. It behaves correctly in a single-threaded environment, but in
a multithreaded environment does not.
Listing 1.1. Non-thread-safe Sequence Generator.
Figure 1.1. Unlucky Execution of UnsafeSequence.Nextvalue .
Search WWH ::




Custom Search