Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Java
Javahard

CompletableFuture — what is it good for and a common pitfall?

Tags
#completablefuture#async#concurrency
Back to categoryPractice quiz

Answer

It represents an async computation that you can compose (`thenApply/thenCompose`) without blocking. A common pitfall is calling `get()/join()` too early (turning it back into blocking code) or forgetting to handle exceptions (`exceptionally/handle`).

CompletableFuture<Integer> result = CompletableFuture
  .supplyAsync(() -> 40)
  .thenApply(x -> x + 2)
  .exceptionally(e -> 0);

System.out.println(result.join());

Advanced answer

Deep dive

`CompletableFuture` lets you build an async pipeline:

  • Transform: `thenApply`
  • Flat-map async stages: `thenCompose`
  • Combine: `thenCombine`, `allOf`, `anyOf`
  • Handle errors: `exceptionally`, `handle`

Common pitfalls

  • Blocking too early with `join()`/`get()` (you lose async benefits).
  • Using the common ForkJoinPool for blocking IO (thread starvation). Use a dedicated `Executor`.
  • Mixing up `thenApply` vs `thenCompose` (nesting futures).

Example

CompletableFuture<User> f = CompletableFuture.supplyAsync(this::loadUser, ioPool)
  .thenCompose(user -> CompletableFuture.supplyAsync(() -> loadProfile(user), ioPool))
  .exceptionally(ex -> fallbackUser());

Practical guidance

  • Always think about which executor runs each stage.
  • Add timeouts and cancellation where appropriate.

Related questions

Java
HashMap vs ConcurrentHashMap: when should you use each?
#java#collections#concurrency
Java
`synchronized` vs `ReentrantLock`: what are the differences?
#java#concurrency#locks
Java
Parallel streams: when can they help and what are common pitfalls?
#java#streams
#parallel
Java
`synchronized` vs `ReentrantLock` - when would you choose one?
#concurrency#locks#synchronized
Java
What does `ThreadLocal` do and what is a common pitfall?
#threadlocal#concurrency#thread-pool
Java
Java Memory Model: what does “happens-before” mean (in simple terms)?
#jmm#happens-before#concurrency