How can I compute sum of very large array concurrently by dividing into multiple CompletableFuture
and trying to compute their result async.
For my simple sample program, I am using array length=4 and dividing into 2 CompletableFuture
, but how can I make the process dynamic if the array size is in millions. Ideally would want to keep the CPU occupied and they should keep giving their result as soon as the complete so that the global sum is returned as soon as possible.
public class Parallelism {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4};
//sum = 10
int n = arr.length;
CompletableFuture<Integer> first = CompletableFuture.supplyAsync(() -> {
return sum(arr, 0, 1);
});
CompletableFuture<Integer> second = CompletableFuture.supplyAsync(() -> {
return sum(arr, 2, n-1);
});
int sum = 0;
sum += first.join();
sum += second.join();
assert sum == 10;
}
private static int sum(int[] arr, int start, int end) {
int sum = 0;
for(int i = start; i <= end; i++) {
sum += arr[i];
}
return sum;
}
}