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:
- Can we use
runAsync()
here? If not, when should we use it? - Why do people use
allOf()
? Should I also use it to check if any of the tasks have exceptions? I sometimes getunreported exception java.lang.InterruptedException; must be caught or declared to be thrown
- What is a more efficient way to calculate the sum of all values in
val
? Can I usethenApply()
?