Java Reference
In-Depth Information
You've now seen two different ways to do parallel computing on a collection: either convert it to
a parallel stream and use operations like map on it, or iterate over the collection and spawn
operations within a CompletableFuture. The latter provides more control using resizing of
thread pools, which helps ensure that your overall computation doesn't block just because all of
your fixed number of threads are waiting for I/O.
Our advice for using these APIs is as follows:
If you're doing computation-heavy operations with no I/O, then the Stream interface gives the
simplest implementation and one likely to be the most efficient (if all threads are compute-bound,
then there's no point in having more threads than processor cores).
On the other hand, if your parallel units of work involve waiting for I/O (including network
connections), then CompletableFuture s give more flexibility and the ability to match the number of
threads to the wait/computer, or W/C, ratio as discussed previously. Another reason to avoid using
parallel streams when I/O waits are involved in the stream-processing pipeline is that the laziness of
streams can make it harder to reason about when the waits actually happen.
You've learned how to take advantage of CompletableFutures both to provide an asynchronous
API to your clients and as the client of a synchronous but slow server. But we performed only a
single time-consuming operation in each Future. In the next section, you'll see how you can use
CompletableFutures to pipeline multiple asynchronous operations, in a declarative style similar
to what you've already learned using the Streams API.
11.4. Pipelining asynchronous tasks
Let's now suppose that all the shops have agreed to use a centralized discount service. This
service uses five different discount codes, and each code has a different discount percentage.
You represent this idea by defining a Discount.Code enumeration, as shown in the following
listing.
Listing 11.13. An enumeration defining the discount codes
public class Discount {
public enum Code {
NONE(0), SILVER(5), GOLD(10), PLATINUM(15), DIAMOND(20);
private final int percentage;
Search WWH ::




Custom Search