Java – the difference between parallel flow and completable future

In the book "Java 8 in action" (urma, Fusco and mycroft), they emphasize that parallel flows internally use a common fork connection pool, which can be configured globally, for example, using system Setproperty (...), which cannot specify a value for a single parallel stream

I've seen that workaround involves running parallel streams in a custom fork join pool

At the end of this book, they have a whole chapter devoted to completable future. During this period, they have a case study. They compare the performance of parallel stream vs and completable future Their performance turns out to be very similar - they emphasize this because they all use the same common pool by default (and therefore the same number of threads)

They continue to show the solution and argue that completable future is better in this case because it can be set to use a custom executor and its user selected thread pool size When they update the solution to take advantage of it, performance improves significantly

This reminds me – if the solution highlighted above is used to do the same thing for the parallel stream version, will the performance advantages be similar, and will the two methods be similar in performance again? In this case, why do people choose completable future instead of parallel flow, because it obviously requires more work from developers

Solution

With all due respect, it depends on the interface you want to support If you want to support asynchronous APIs, for example

CompletableFuture<String> downloadHttp(URL url);

In this case, only the achievable future makes sense, because you may want to perform other unrelated operations while waiting for the data to decline

On the other hand, parallelstream () is best suited for CPU bound tasks, where you want each task to perform some part of the work That is, each thread uses different data to do the same thing You mean it's easier to use, too

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>