Java Reference
In-Depth Information
futures.add(printExecutor.submit(() -> {
String primeString = stringFuture.get();
System.out.println(primeString);
return null;
}
)
);
}
// Signal that there will be no more tasks added
executor.shutdown();
printExecutor.shutdown();
// Wait for everything to complete and check for errors
futures.parallelStream().forEach(future -> {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
);
}
public static void main(String[] args) {
DemoRunner.run(Listing3::printPrimes);
}
}
This code is much nicer compared to Listing 6-2. There is no need for us to declare flags or hand-off
queues; instead, we just pass one Future into the work for another, and we work with the resulting futures.
We still get our saturated processor cores, and we still get our dedicated thread to I/O. You may be concerned
about the overhead incurred by the executor classes as opposed to our “hand-tuned” implementation, but
the result is actually half a second faster on my computer, coming in at 14.0 seconds.
If you were paying close attention, you probably caught the invocation of futures.parallelStream() .
We saw in the last chapter how streams can be set to process in parallel, with the result being some
additional transparent concurrency. Here, the parallelism allows us to check the futures for errors very
quickly, and all it cost was a method call. That is very powerful, but we are not quite ready to get into that
concurrency approach: we will get there in a later section of this chapter. There is still more to be done here
with Java's preexisting concurrency tools!
Lambdas and the ThreadPoolExecutor
This gives you the basic idea about how lambdas make life with executors so much nicer. There is one
particular place, however, where the ability to define interface implementations inline is incredibly helpful,
and that's with the ThreadPoolExecutor .
The ThreadPoolExecutor is an extremely customizable implementation of the ExecutorService class.
Many programmers (including your author) really like to twiddle knobs, and this class gives you plenty of
knobs to keep you busy. Some of those knobs are numerical values, but there are many callbacks available
 
Search WWH ::




Custom Search