2

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
Trein
  • 3,658
  • 27
  • 36
Malkeith Singh
  • 235
  • 1
  • 8

2 Answers2

4

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.

the8472
  • 40,999
  • 5
  • 70
  • 122
1

The way that it was implemented above, there's no difference. The advantage of using CompletableFuture API is that you can pass a custom Executor if you want to have more control over the threads and/or implement some async semantic.

Trein
  • 3,658
  • 27
  • 36
  • 1
    but you can choose on which executor parallel streams run, as long as it is a FJP. https://stackoverflow.com/a/22269778/1362755 – the8472 Sep 07 '19 at 14:40
  • 2
    @the8472 as Henry Ford said, you can have the Model T in your favorite color, as long as your favorite color is black. So yes, you can choose the executor for the parallel stream, as long as it is a FJP. And you have to live with the fact that this is an undocumented feature of this particular implementation. – Holger Sep 10 '19 at 11:37