The most efficient way to stream on a futures list

I call the async client method by streaming through a list of objects. The method returns Future.

What is the best way to iterate over the list of futures returned after the call (to handle this future, which comes first)?

Note. Asynchronous client returns only "Future is not CompletedFuture".

Below is the code:

List<Future<Object>> listOfFuture = objectsToProcess.parallelStream() .map((object) -> { /* calling an async client returning a Future<Object> */ }) .collect(Collectors.toList()); 
+5
source share
1 answer

Having this List<Future<Object>> list, I have to send it to my own pool instead of using the default parallel thread processing.

This is because the api stream uses a common pool for parallel processing, and you call get on these futures (if it takes a lot of time to process) - you will block all other operations of the stream that use parallel operations in your application until it done.

It will be something like this:

 forJoinPool.submit( () -> list.stream().parallel().map(future -> future.get()).collect(Collectors.toList())).get(); 

I would go with a custom pool as shown here

+3
source

Source: https://habr.com/ru/post/1266349/


All Articles