Java Reference
In-Depth Information
and use a timed
get
to fetch each result sequentially via its
Future
, but there is an even
easierway—
invokeAll
.
orService
and retrieve the results. The
invokeAll
method takes a collection of tasks
and returns a collection of
Future
s. The two collections have identical structures;
in-
vokeAll
adds the
Future
s to the returned collection in the order imposed by the task col-
lection's iterator, thus allowing the caller to associate a
Future
with the
Callable
it rep-
resents. The timed version of
invokeAll
will return when all the tasks have completed, the
calling thread is interrupted, or the timeout expires. Any tasks that are not complete when the
timeout expires are cancelled. On return from
invokeAll
, each task will have either com-
pleted normally or been cancelled; the client code can call
get
or
isCancelled
to find
out which.
Summary
Structuring applications around the execution of
tasks
can simplify development and facilit-
ate concurrency. The
Executor
framework permits you to decouple task submission from
execution policy and supports a rich variety of execution policies; whenever you find your-
self creating threads to perform tasks, consider using an
Executor
instead. To maximize
the benefit of decomposing an application into tasks, you must identify sensible task bound-
aries. In some applications, the obvious task boundaries work well, whereas in others some
analysis may be required to uncover finer-grained exploitable parallelism.