Parallel streams Vs Completeable Future in java 8

Malkeith Singh :

What is the difference between:

List<String> parra = list.parallelStream()
    .map(heavyPrcessingFunction)
    .collect(Collectors.toList());

and this (apart from the second being a bit complex):

List<CompletableFuture<Void>> com = list.stream()
    .map(x-> CompletableFuture.runAsync(() -> heavyPrcessingFunction.apply(x)))
    .collect(Collectors.toList());

CompletableFuture.allOf(com.toArray(new CompletableFuture[0])).join();
// get all of strings from com now
the8472 :

Semantically they are quite similar, it mostly is a matter of overhead.

For the 2nd approach you have to create a CF for each entry in the list and submit them individually to the common FJP.

Parallel streams on the other hand can be implemented by chunking the input list into a few large slices, submitting only those slices as a tasks to the common pool and then having a thread essentially loop over the slice instead of having to pick up and unwrap future by future from its work queue. Additionally the stream implementation means that not just the map operation but also the collect step is aware of parallel execution and can thus optimize it.

Fewer allocations, fewer expensive operations on concurrent data structures, simpler code.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142421&siteId=1
Recommended