Java Reference
In-Depth Information
8.5. Parallelizing Recursive Algorithms
The page rendering examples in Section 6.3 went through a series of refinements in search of
exploitable parallelism. The first attempt was entirely sequential; the second used two threads
but still performed all the image downloads sequentially; the final version treated each image
download as a separate task to achieve greater parallelism. Loops whose bodies contain non-
trivial computation or perform potentially blocking I/O are frequently good candidates for
parallelization, as long as the iterations are independent.
If we have a loop whose iterations are independent and we don't need to wait for all of them to
complete before proceeding, we can use an Executor to transform a sequential loop into a
parallel one, as shown in processSequentially and processInParallel in List-
ing 8.10 .
Listing 8.10. Transforming Sequential Execution into Parallel Execution.
A call to processInParallel returns more quickly than a call to processSequen-
tially because it returns as soon as all the tasks are queued to the Executor , rather than
waiting for them all to complete. If you want to submit a set of tasks and wait for them all
to complete, you can use ExecutorService.invokeAll ; to retrieve the results as they
become available, you can use a CompletionService , as in Renderer on page 130 .
Sequential loop iterations are suitable for parallelization when each iteration is independent
of the others and the work done in each iteration of the loop body is significant enough to
offset the cost of managing a new task.
Search WWH ::




Custom Search