Video in progress

Strong Middle 🧵 Concurrency

On which thread do thenApply and thenApplyAsync run in CompletableFuture?

thenApply runs on the calling thread if the previous stage has already finished, and if it hasn't, on the thread that completes it. thenApplyAsync is always submitted to an executor, and if you don't pass one, to ForkJoinPool.commonPool().

📖 Answer

This question looks simple, but half of the latency problems in prod come from here.

CompletableFuture<User> user = CompletableFuture.supplyAsync(this::loadUser, ioPool);

user.thenApply(this::toDto);              // on an ioPool thread, or on the caller
user.thenApplyAsync(this::toDto);         // on commonPool
user.thenApplyAsync(this::toDto, cpuPool); // explicitly on cpuPool

The rule for thenApply: whichever thread completed the future runs the callback. If the future is already done, it runs on the very thread that called thenApply. So you can't know in advance where it will run.

When this hurts:

  • the HTTP client's IO thread completes the future, and you do heavy computation or a blocking call inside thenApply, so the client's event loop freezes;
  • you use the Async version without an executor, so the whole application shares a single commonPool, and its size is CPU - 1. If you do blocking IO there, parallel streams slow down too.

My rule: a light transformation gets thenApply; a heavy or blocking step gets thenApplyAsync(fn, explicitExecutor). I never send IO to commonPool.