Video in progress

An HTTP call was made inside a parallel stream and the whole service "froze". What happened, and how do you fix it?

All parallel streams share one ForkJoinPool.commonPool(), whose size is the core count minus one. Blocking I/O occupies the pool threads, and other parallel streams and the default executor of CompletableFuture stall as well. For I/O you need a separate executor or virtual threads.

📖 Answer

A typical picture:

List<Price> prices = productIds.parallelStream()
        .map(id -> pricingClient.fetch(id))   // each takes 300 ms of network
        .toList();

On a 4-core pod the common pool has 3 workers (plus the calling thread). 200 IDs means about 50 waves × 300 ms = 15 seconds. If several requests arrive at the same time, they wait on each other. Meanwhile, if somewhere else a CompletableFuture.supplyAsync(...) was called without an executor, it's in the same pool and waits too. In a thread dump, all the ForkJoinPool.commonPool-worker-* threads are sitting in SocketInputStream.read.

What not to do: set java.util.concurrent.ForkJoinPool.common.parallelism=64. That is a global change for the whole JVM and hides the problem.

A trick you sometimes see is pool.submit(() -> list.parallelStream()...).get() inside your own ForkJoinPool. It works, because a parallel stream uses the current FJP, but that is an undocumented implementation detail. I don't rely on it in prod code.

Correct solutions:

// Java 21: a virtual thread per call
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
    List<Future<Price>> fs = productIds.stream()
            .map(id -> exec.submit(() -> pricingClient.fetch(id)))
            .toList();
    List<Price> prices = new ArrayList<>();
    for (Future<Price> f : fs) prices.add(f.get());
}

Or CompletableFuture with a bounded executor. What matters is limiting the number of concurrent calls (a semaphore, a bulkhead), otherwise you hammer the external service with 200 parallel requests. Often the best move is to check whether the external API has a batch endpoint: one request instead of 200.