簡體   English   中英

如何有效地使用 CompletableFuture 到 map 每個輸入的異步任務

[英]How to efficiently use CompletableFuture to map async task per input

我想返回 map,包括所有鍵到值的映射,即 API 對這些鍵的響應。 我為此使用CompletableFutureGuava 下面是我的嘗試。 是否有任何其他標准方法可以通過 Java 8 和線程 API 實現相同的目標?

Map 是id -> apiResponse(id)

    
    public static List<String> returnAPIResponse(Integer key) {
        return Lists.newArrayList(key.toString() + " Test");
    }

    public static void main(String[] args) {
        List<Integer> keys = Lists.newArrayList(1, 2, 3, 4);

        List<CompletableFuture<SimpleEntry<Integer, List<String>>>> futures = keys
            .stream()
            .map(key -> CompletableFuture.supplyAsync(
                () -> new AbstractMap.SimpleEntry<>(key, returnAPIResponse(key))))
            .collect(Collectors.toList());

        System.out.println(
            futures.parallelStream()
            .map(CompletableFuture::join)
            .collect(Collectors.toList()));

    }

這里有一個有趣的行為,我會盡力解釋。 讓我們從簡單的開始,讓我們暫時忘記CompletableFuture並簡單地使用普通的parallelStream來執行此操作,並添加了一個小的調試步驟:

List<Integer> keys = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);

Map<Integer, List<String>> result =
    keys.parallelStream()
        .map(x -> new AbstractMap.SimpleEntry<>(x, returnAPIResponse(x)))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

System.out.println("parallelism : " + pool.getParallelism() + " current : " + pool.getPoolSize());

在我的機器上,打印:

parallelism : 11 current : 11

我假設您已經知道parallelStream的操作是在commonForkJoinPool中執行的。 output 的含義可能也很明顯: 11 threads可用並且全部使用。

我現在將稍微修改您的示例:

List<Integer> keys = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);

ForkJoinPool pool = ForkJoinPool.commonPool();
ExecutorService supplyPool = Executors.newFixedThreadPool(2);

Map<Integer, List<String>> result =
keys.parallelStream()
    .map(x -> CompletableFuture.supplyAsync(
             () -> new AbstractMap.SimpleEntry<>(x, returnAPIResponse(x)),
             supplyPool
    ))
    .map(CompletableFuture::join)
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

 System.out.println("parallelism : " + pool.getParallelism() + " current : " + pool.getPoolSize());

這實際上只是一個重要的變化,我會讓你的supplyAsync在它自己的線程池中運行; rest 是一樣的。 運行它,顯示:

parallelism : 11 current : 16

驚喜。 創建了更多線程然后我們想要什么? 好吧, getPoolSize的文檔說:

返回已啟動但尚未終止的工作線程數。 此方法返回的結果可能與 getParallelism 在創建線程以在其他線程被協作阻塞時保持並行性時有所不同。

您的情況下的阻塞是通過map(CompletableFuture::join)發生的。 您已經有效地阻止了來自ForkJoinPool的工作線程,它通過旋轉另一個工作線程來彌補這一點。


如果您不想遇到這樣的意外:

List<CompletableFuture<AbstractMap.SimpleEntry<Integer, List<String>>>> list =
keys.stream()
    .map(x -> CompletableFuture.supplyAsync(
         () -> new AbstractMap.SimpleEntry<>(x, returnAPIResponse(x)),
         supplyPool
     ))
    .collect(Collectors.toList());

CompletableFuture.allOf(list.toArray(new CompletableFuture[0])).join();

Map<Integer, List<String>> result =
list.stream()
    .map(CompletableFuture::join)
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

因為ForJoinPool的工作線程上沒有join ,所以您可以刪除parallelStream 然后我仍然阻止通過以下方式獲得結果:

CompletableFuture.allOf(list.toArray(new CompletableFuture[0])).join();

但不會產生補償線程。 而且因為CompletableFuture.allOf返回CompletableFuture<Void> ,我需要再次 stream 來獲得結果。

不要讓最后一個 stream 操作中的.map(CompletableFuture::join)欺騙你,因為之前的CompletableFuture::allOf已經阻塞並等待所有任務完成,所以沒有阻塞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM