Java: splitting work across a thread pool

Data parallelism splits one large job into independent pieces that run at the same time and then combines the results. In Java, an ExecutorService manages a pool of worker threads. submit takes a task and returns a Future, which is a handle for a result that will exist later.

Java
import java.util.*;
import java.util.concurrent.*;

class Main {
  public static void main(String[] args) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(4);
    List<Future<Long>> parts = new ArrayList<>();
    for (int start = 1; start <= 1000; start += 250) {
      final int from = start;
      parts.add(pool.submit(() -> {
        long sum = 0;
        for (int n = from; n < from + 250; n++) {
          sum += (long) n * n;
        }
        return sum;
      }));
    }
    long total = 0;
    for (Future<Long> part : parts) {
      total += part.get();
    }
    pool.shutdown();
    System.out.println("sum of squares 1..1000 = " + total);
  }
}
Read the full lesson