ExecutorService + Futures
Time O(n / threads) ideal wall time Space O(threads)Fixed pool; submit one Callable per chunk; sum the results; shut the pool down in finally.
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], threads = 3state(vars)
Step 1/5Chunk size = (10 + 3 − 1) / 3 = 4, so the pieces are indexes 0–3, 4–7 and 8–9.
import java.util.*;
import java.util.concurrent.*;
class Solution {
public long parallelSum(int[] nums, int threads) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(threads);
try {
int n = nums.length, chunk = Math.max(1, (n + threads - 1) / threads);
List<Future<Long>> parts = new ArrayList<>();
for (int start = 0; start < n; start += chunk) {
int s = start, e = Math.min(n, start + chunk);
parts.add(pool.submit(() -> {
long t = 0;
for (int i = s; i < e; i++) t += nums[i];
return t;
}));
}
long total = 0;
for (Future<Long> f : parts) total += f.get();
return total;
} finally {
pool.shutdown();
}
}
}Verdict: The basic fork-join shape.