我有一个异步执行的查询的输入流。我想确保当我使用可完成未来::join
时,这些要求的结果将按照输入查询流的顺序收集。
这是我的代码的样子:
queries.stream()
.map(query -> CompletableFuture.supplyAsync(() -> {
try {
return SQLQueryEngine.execute(query);
} catch (InternalErrorException e) {
throw new RuntimeException(e);
}
}))
.map(CompletableFuture::join)
.collect(Collectors.toList());
SQLQueryEngine。执行(查询);返回列表
您可能指的是.持平地图
,是的,它将保留顺序。
考虑显式地将Executor
传递给supplyAsync
,以避免在中调度IO绑定的sql查询。
正如@Ruben指出的那样,在提交当前线程之后和提交下一个查询之前,您将立即加入当前线程中的每个任务,这可能是一个错误。您应该先提交所有查询,然后才能开始加入。
你可以这样做(静态导入 toList
):
queries.stream()
.map(query -> CompletableFuture.supplyAsync(...))
.collect(toList())
.stream()
.map(CompletableFuture::join)
.collect(toList());