我通过流式传输对象列表来调用异步客户端方法。该方法返回Future。
迭代调用后返回的Futures列表的最佳方法是什么(以便处理那些首先出现的Future)?
注意:异步客户端仅返回Future not CompletableFuture。
以下是代码:
List<Future<Object>> listOfFuture = objectsToProcess.parallelStream()
.map((object) -> {
/* calling an async client returning a Future<Object> */ })
.collect(Collectors.toList());
答案 0 :(得分:5)
拥有此List<Future<Object>>
列表,我会将其提交到自定义池,而不是使用默认流并行处理。
这是因为流api使用公共池进行并行处理,您将在那些Futures上调用get
(如果需要大量时间进行处理) - 您将阻止所有其他使用并行操作的流操作你的申请,直到这个完成。
这有点像这样:
forJoinPool.submit( () -> list.stream().parallel().map(future -> future.get()).collect(Collectors.toList())).get();
我会选择显示here
的自定义池