Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

26 The Concurrency Utilities


F


rom the start, Java has provided built-in support for multithreading and synchronization.
For example, new threads can be created by implementingRunnableor by extending
Thread, synchronization is available by use of thesynchronizedkeyword, and
interthread communication is supported by thewait( )andnotify( )methods that are
defined byObject. In general, this built-in support for multithreading was one of Java’s
most important innovations and is still one of its major strengths.
However, as conceptually pure as Java’s original support for multithreading is, it is not
ideal for all applications—especially those that make extensive use of multiple threads. For
example, the original multithreading support does not provide several high-level features,
such as semaphores, thread pools, and execution managers, that facilitate the creation of
intensive concurrent programs.
It is important to explain at the outset that many Java programs make use of multithreading
and are therefore “concurrent.” For example, most applets use multithreading. However, as
it is used in this chapter, the termconcurrent programrefers to a program that makesextensive,
integraluse of concurrently executing threads of execution. An example of such a program
is one that uses separate threads to simultaneously compute the partial results of a larger
computation. Another example is a program that coordinates the activities of several threads,
each of which seeks access to information in a database. In this case, read-only accesses
might be handled differently from those that require read/write capabilities.
To handle the needs of a concurrent program, JDK 5 added theconcurrency utilities,also
commonly referred to as theconcurrent API.The concurrency utilities supply many features
that had long been wanted by programmers who develop concurrent applications. For
example, they offer the semaphore, cyclic barriers, countdown latches, thread pools,
executionmanagers, locks, several concurrent collections, and a streamlined way to
use threads toobtain computationalresults.
The concurrent API is quite large, and many of the issues surrounding its use are quite
complex. It is beyond the scope of this book to discuss all of its facets. Moreover, the alternatives
offered by the concurrency utilities are not designed for use by most programs. Simply put:
Unless you are writing programs with a significant amount of concurrency, in most cases,
Java’s traditional support for multithreading and synchronization is not only sufficient, but
in many cases also is preferable to the capabilities offered by the concurrent API.
The preceding paragraph notwithstanding, it is important for all programmers to have a
general, working knowledge of the concurrent API. Furthermore, there are some parts of it,


787

Free download pdf