Java Reference
In-Depth Information
A : The concurrency utilities, which are packaged in java.util.concurrent (and its sub-
packages), support concurrent programming. Among several other items, they offer
synchronizers, thread pools, execution managers, and locks that expand your control
over thread execution. One of the most exciting features of the concurrent API is the
Fork/Join Framework.
The Fork/Join Framework supports what is often termed parallel programming . This is
the name commonly given to the techniques that take advantage of computers that contain
two or more processors (including multicore systems) by subdividing a task into subtasks,
with each subtask executing on its own processor. As you can imagine, such an approach
can lead to significantly higher throughput and performance. The key advantage of the
Fork/Join Framework is ease of use; it streamlines the development of multithreaded code
that automatically scales to utilize the number of processors in a system. Thus, it facilit-
ates the creation of concurrent solutions to some common programming tasks, such as
performing operations on the elements of an array. The concurrency utilities in general,
and the Fork/Join Framework specifically, are features that you will want to explore after
you have become more experienced with multithreading.
Thread Communication Using notify( ), wait( ), and notifyAll( )
Consider the following situation. A thread called T is executing inside a synchronized
method and needs access to a resource called R that is temporarily unavailable. What
should T do? If T enters some form of polling loop that waits for R, T ties up the object,
preventing other threads' access to it. This is a less than optimal solution because it par-
tially defeats the advantages of programming for a multithreaded environment. A better
solution is to have T temporarily relinquish control of the object, allowing another thread
to run. When R becomes available, T can be notified and resume execution. Such an ap-
proach relies upon some form of interthread communication in which one thread can notify
another that it is blocked and be notified that it can resume execution. Java supports inter-
thread communication with the wait( ) , notify( ) , and notifyAll( ) methods.
The wait( ) , notify( ) , and notifyAll( ) methods are part of all objects because they are
implemented by the Object class. These methods should be called only from within a syn-
chronized context. Here is how they are used. When a thread is temporarily blocked from
running, it calls wait( ) . This causes the thread to go to sleep and the monitor for that ob-
ject to be released, allowing another thread to use the object. At a later point, the sleeping
thread is awakened when some other thread enters the same monitor and calls notify( ) , or
notifyAll( ) .
Following are the various forms of wait( ) defined by Object :
Search WWH ::




Custom Search