简体   繁体   中英

Using CompletableFuture for asynchronous calls in loop

I am trying to create an asynchronous call first time. I came across CompletableFuture [https://stackoverflow.com/questions/59183298/how-to-get-result-from-completablefuturelistcustomobject-in-java-8]. Hence, I tried as follows:

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class test {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Hashtable<Integer, Integer> hash_table =
                new Hashtable<Integer, Integer>();
        hash_table.put(0, 10);
        hash_table.put(1, 20);
        hash_table.put(2, 30);
        int sum = 0;
        List<CompletableFuture<Integer>> val = new ArrayList<>();
        for (int i = 0; i < hash_table.size(); i++) {
            final int finali = i;
            val.add(CompletableFuture.supplyAsync(() -> computeArea(hash_table.get(finali))));
        }
        for (int i=0;i<val.size();i++){
            sum+= val.get(i).get();
        }
        System.out.println(sum);
    }
    private static int computeArea(int a) {
        return a * a;
    }
}

Further questions:

  1. Can we use runAsync() here? If not, when should we use it?
  2. Why do people use allOf() ? Should I also use it to check if any of the tasks have exceptions? I sometimes get unreported exception java.lang.InterruptedException; must be caught or declared to be thrown unreported exception java.lang.InterruptedException; must be caught or declared to be thrown
  3. What is a more efficient way to calculate the sum of all values in val ? Can I use thenApply() ?

Can we use runAsync() here? If not, when should we use it?

Yes, you would use run async. The purpose of the method is to run each task in parallel rather than one after another sequentially.

Why do people use allOf()? Should I also use it to check if any of the tasks have exceptions?

The question is subjective but you can use it to check if exceptions have finished erroneously. You can also use it to ensure that all tasks have completed, or if some have not. There are a lot of applications for CompletableFuture#allOf.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM