Java Concurrency Interview

CompletableFuture and async composition question 93 of 180 mid

What is the difference between thenApply and thenCompose?

It is map versus flatMap. If your function returns a plain value, use thenApply. If it returns another CompletableFuture, which is what any further async call gives you, thenApply wraps it and you end up with CompletableFuture<CompletableFuture<User>>. thenCompose unwraps it for you.

cf.thenApply(id -> loadUser(id));      // CF<CF<User>>  -- almost always a mistake
cf.thenCompose(id -> loadUser(id));    // CF<User>

thenCombine is the third member: two independent futures plus a BiFunction when you want both results and neither depends on the other.

completablefuture api

Quiz yourself on CompletableFuture and async composition Suggest a correction