gpt4 book ai didi

concurrency - CompletableFuture supplyAsync 与 Stream.map()

转载 作者:行者123 更新时间:2023-12-04 02:54:55 24 4
gpt4 key购买 nike

伙计们!我有一个问题:这段代码是做什么的:

Collection<Contract.class> contracts = fillTheCollectionFromDb();
contracts.stream().filter(condition)
.map(contractItem ->
CompletableFuture.supplyAsync(() ->
{T result = getAnotherDataFromDb(contractItem);
return result;}, Executor.class)
)//end .map
.map(CompletableFuture::join).collect(Collectors.toList());

最佳答案

这段代码相当于:

Collection<Contract> contracts = fillTheCollectionFromDb();
contracts.stream().filter(condition)
.map(this::getAnotherDataFromDb)
.collect(Collectors.toList());

要使这个程序真正并行,应该对其进行修改。首先,并行启动对数据库的所有请求:

Collection<Contract> contracts = fillTheCollectionFromDb();
List<CompletableFuture> futures = contracts.stream().filter(condition)
.map(contractItem ->
CompletableFuture.supplyAsync(
()->getAnotherDataFromDb(contractItem),
executor)
)//end .map
.collect(Collectors.toList());

然后才收集所有结果:

List results = futures.stream
.map(CompletableFuture::join)
.collect(Collectors.toList());

关于concurrency - CompletableFuture supplyAsync 与 Stream.map(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53435098/

24 4 0