Sum a large array using multiple threads. Compare single-threaded, ExecutorService chunks, ForkJoin, parallel streams and virtual threads.
Problem
Sum 50 million numbers as fast as possible using all CPU cores, and explain when parallelism helps.
Pattern
Divide and combine (fork/join): split the input into independent chunks, process them concurrently, combine the partial results. CPU-bound work scales with cores, not with thread count.
import java.util.stream.IntStream;
final class Data {
static final int[] NUMBERS = IntStream.range(0, 50_000_000).map(i -> i % 100).toArray();
}Approach 1: Single thread (the baseline you must beat)
class SumSequential {
static long sum(int[] a) {
long s = 0;
for (int x : a) s += x;
return s;
}
}Approach 2: ExecutorService with one chunk per core (Java 5)
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class SumExecutor {
static long sum(int[] a) throws Exception {
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(threads);
try {
List<Future<Long>> parts = new ArrayList<>();
int chunk = (a.length + threads - 1) / threads;
for (int t = 0; t < threads; t++) {
int from = t * chunk, to = Math.min(a.length, from + chunk);
parts.add(pool.submit(() -> { long s = 0; for (int i = from; i < to; i++) s += a[i]; return s; }));
}
long total = 0;
for (Future<Long> f : parts) total += f.get();
return total;
} finally {
pool.shutdown();
}
}
}Approach 3: ForkJoin RecursiveTask (Java 7, work stealing)
Split recursively until a chunk is small enough; idle workers steal subtasks from busy ones, balancing uneven work.
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
class SumForkJoin extends RecursiveTask<Long> {
private static final int THRESHOLD = 100_000;
private final int[] a;
private final int from, to;
SumForkJoin(int[] a, int from, int to) { this.a = a; this.from = from; this.to = to; }
@Override protected Long compute() {
if (to - from <= THRESHOLD) { long s = 0; for (int i = from; i < to; i++) s += a[i]; return s; }
int mid = (from + to) >>> 1;
SumForkJoin left = new SumForkJoin(a, from, mid);
left.fork(); // run asynchronously
long right = new SumForkJoin(a, mid, to).compute(); // compute the other half in this thread
return right + left.join();
}
static long sum(int[] a) { return ForkJoinPool.commonPool().invoke(new SumForkJoin(a, 0, a.length)); }
}Approach 4: Parallel streams (Java 8): the same fork/join with one line
import java.util.Arrays;
class SumParallelStream {
static long sum(int[] a) { return Arrays.stream(a).parallel().asLongStream().sum(); }
}Approach 5: Virtual threads (Java 21): the wrong tool for CPU-bound work
Virtual threads help when tasks wait (I/O). For pure computation they still run on the carrier threads (one per core), so they cannot beat Approaches 2–4; creating thousands of them for CPU work only adds overhead.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class SumVirtual {
static long sum(int[] a, int tasks) throws Exception {
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<Long>> parts = new ArrayList<>();
int chunk = (a.length + tasks - 1) / tasks;
for (int t = 0; t < tasks; t++) {
int from = t * chunk, to = Math.min(a.length, from + chunk);
parts.add(ex.submit(() -> { long s = 0; for (int i = from; i < to; i++) s += a[i]; return s; }));
}
long total = 0;
for (Future<Long> f : parts) total += f.get();
return total;
}
}
}
class ParallelSumDemo {
public static void main(String[] args) throws Exception {
int[] a = Data.NUMBERS;
for (int round = 0; round < 2; round++) { // second round shows warmed-up JIT timings
long t = System.nanoTime(); long s1 = SumSequential.sum(a); long d1 = ms(t);
t = System.nanoTime(); long s2 = SumExecutor.sum(a); long d2 = ms(t);
t = System.nanoTime(); long s3 = SumForkJoin.sum(a); long d3 = ms(t);
t = System.nanoTime(); long s4 = SumParallelStream.sum(a); long d4 = ms(t);
t = System.nanoTime(); long s5 = SumVirtual.sum(a, 1000); long d5 = ms(t);
System.out.printf("same result: %b | sequential %d ms, executor %d ms, forkjoin %d ms, parallel stream %d ms, virtual %d ms%n",
s1 == s2 && s2 == s3 && s3 == s4 && s4 == s5, d1, d2, d3, d4, d5);
}
}
static long ms(long start) { return (System.nanoTime() - start) / 1_000_000; }
}Feasible → optimal
For memory-bound work like summing, the sequential loop is already fast and parallel versions gain a few times at best (memory bandwidth, not CPU, is the limit). ExecutorService chunks, ForkJoin and parallel streams all scale CPU-bound work with cores; parallel streams are the simplest, ForkJoin gives control over granularity, and virtual threads are for I/O, not computation. Always measure (ideally with JMH) before parallelising.
Follow-up questions interviewers ask
Try answering each one before you open it.
Related (same pattern): parallel merge sort.
A RecursiveAction that sorts halves in parallel (fork one half, compute the other) and merges; below a threshold switch to Arrays.sort. The JDK already provides Arrays.parallelSort, which does this.
Related (same pattern): count word frequencies across many files in parallel.
Process each file as a task (ExecutorService or files.parallelStream()), produce a partial Map<String, Long> per task, then merge maps (or use groupingByConcurrent into a shared ConcurrentHashMap). File reading is I/O, so virtual threads are appropriate for the reading part.