Video in progress
Why is it dangerous to do blocking I/O inside CompletableFuture.supplyAsync?
If you don't pass an executor, the task runs in ForkJoinPool.commonPool(). It is one pool for the whole JVM and it is small (number of cores minus 1). Blocking calls fill it up, and parallel streams and other async code stall too.
📖 Answer
The classic case:
List<CompletableFuture<Rate>> futures = banks.stream()
.map(b -> CompletableFuture.supplyAsync(() -> b.fetchRate())) // HTTP, 2 seconds
.toList();
In a 4-core container the common pool has 3 threads. With 50 banks, the 50 HTTP calls pass through three threads in turn, for a total of about 34 seconds. Meanwhile a parallelStream() somewhere else in the application waits too, because it uses the same pool.
There is another trap in containers: if the CPU limit is 1 or 2, the common pool parallelism drops to 1. In that case CompletableFuture doesn't use the commonPool at all and creates a new thread for every async task, which is unexpected behavior.
The solution is a separate executor for I/O:
ExecutorService io = Executors.newVirtualThreadPerTaskExecutor(); // Java 21
List<CompletableFuture<Rate>> futures = banks.stream()
.map(b -> CompletableFuture.supplyAsync(b::fetchRate, io)
.orTimeout(3, TimeUnit.SECONDS))
.toList();
On Java 17, a bounded ThreadPoolExecutor, sized by the number of parallel requests the external service can handle.
The same rule applies to all the *Async methods like thenApplyAsync: the variant without an executor goes to the common pool. In code review, when I see supplyAsync( without a second argument, I always ask about it.
Sign up to mark studied questions and save your progress.