Java Reference
In-Depth Information
three operations to it, perhaps mapping the objects in the collection to sum two of their fields,
then filtering the sums satisfying some criterion, and then sorting the result, you'll make three
separate traversals of the collection. The Streams API instead lazily forms these operations into
a pipeline, and then does a single stream traversal performing all the operations together. This is
much more efficient for large datasets, and for reasons such as memory caches, the larger the
dataset the more important it is to minimize the number of traversals.
The other, no less important, reasons concern the ability to process elements in parallel, which
is vital to efficiently exploit multicore CPUs. Streams, in particular the method parallel, allow a
stream to be marked as suitable for parallel processing. Recall here that parallelism and mutable
state fit badly together, so core functional concepts (side-effect-free operations and methods
parameterized with lambdas and method references that permit internal iteration instead of
external iteration, as discussed in chapter 4 ) are central to exploiting streams in parallel using
map, filter, and the like.
Let's now look at how these ideas, which we introduced in terms of streams, have a direct analog
in the design of CompletableFuture.
16.1.3. CompletableFuture
Java has provided the Future interface since Java 5. Futures are useful for exploiting multicore
because they allow a task to be spawned onto another thread or core and allow the spawning
task to continue executing along with the spawned task. When the spawning task needs the
result, it can use the get method to wait for the Future to complete (produce its value).
Chapter 11 explains the Java 8 CompletableFuture implementation of Future. Again this exploits
lambdas. A useful, if slightly imprecise, motto is that “Completable-Future is to Future as
Stream is to Collection.” Let's compare:
Stream lets you pipeline operations and provides behavior parameterization with map , filter , and
the like, thus avoiding the boilerplate code you typically have to write using iterators.
Similarly, CompletableFuture provides operations such as thenCompose , thenCombine , and
allOf , which give functional-programming-style concise encodings of common design patterns
involving Future s, and let you avoid similar imperative-style boilerplate code.
This style of operations, albeit in a simpler scenario, also applies to the Java 8 operations on
Optional, which we now revisit.
 
Search WWH ::




Custom Search