![](/img/trans.png)
[英]Java completableFuture: how to parallelize several CompletableFutures
[英]CompletableFuture: How to apply a function to multiple CompletableFutures?
假設我有3次下載,被定為可完成的期貨:
CompletableFuture<Doc> dl1 = CompletableFuture.supplyAsync(() -> download("file1"));
CompletableFuture<Doc> dl2 = CompletableFuture.supplyAsync(() -> download("file2"));
CompletableFuture<Doc> dl3 = CompletableFuture.supplyAsync(() -> download("file3"));
然后所有這些都需要以相同的方式處理
CompletableFuture<String> s1 = dl1.thenApply(Doc::getFilename);
CompletableFuture<String> s2 = dl2.thenApply(Doc::getFilename);
CompletableFuture<String> s3 = dl3.thenApply(Doc::getFilename);
您可以想象同時應用多個功能。
根據DRY原理,此示例似乎不合適。 因此,我正在尋找一種解決方案,以定義僅並行執行3次的1個工作流程。
如何做到這一點?
我嘗試了allOf
,但是有兩個問題:1)開始阻塞; 2)返回類型只能run
東西,而不能處理它。
Stream.of("file1", "file2", "file3") // or your input in any other format, that can easily be transformed to a stream...
// .parallel() // well... depends...
.map(s -> CompletableFuture.supplyAsync(() -> download(s)))
.map(dl -> dl.thenApply(Doc::getFilename))
.map(CompletableFuture::join) // if you want to have all the results collected
.collect(Collectors.toList());
當然,兩個map
調用也可以合並。 但是至少您不會將所有內容都寫x次...如果您不喜歡List
的集合,還可以在其上調用其他名稱,例如.forEach(System.out::println)
。 .forEach
的好處是,只要響應可用,就會立即調用使用者。
還是經典之作:只需在輸入中使用循環和列表/數組,但與使用流相比,您可能需要做更多的工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.