Creating and Completing CompletableFutures
Use supplyAsync, runAsync, completedFuture, and manually complete futures with complete and completeExceptionally.
Creating and Completing CompletableFutures is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is CompletableFuture?
CompletableFuture<T> (Java 8+) represents an asynchronous computation that can be explicitly completed, chained, and combined. It implements both Future and CompletionStage.
supplyAsync: Starting an Async Computation
CompletableFuture.supplyAsync() runs a Supplier on the common ForkJoinPool and returns a future of the result.
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// runs on ForkJoinPool.commonPool()
return fetchDataFromNetwork();
});
System.out.println("Non-blocking — this runs immediately");runAsync: Fire and Forget
runAsync() runs a Runnable asynchronously and returns CompletableFuture<Void>. Use it when you don't need a result.
CompletableFuture<Void> task = CompletableFuture.runAsync(() ->
sendEmail("user@example.com", "Welcome!"));
task.thenRun(() -> System.out.println("Email sent"));Custom Executor
Pass a custom Executor to control the thread pool used for the computation — essential in web applications where you want to avoid blocking the common pool.
ExecutorService pool = Executors.newFixedThreadPool(10);
CompletableFuture<User> future = CompletableFuture.supplyAsync(
() -> userService.findById(42L), pool
);completedFuture: Already-Done Value
CompletableFuture.completedFuture(value) returns an already-completed future. Useful for testing or when you have an immediate value to return in an async pipeline.
CompletableFuture<String> cached = CompletableFuture.completedFuture("cached-value");
cached.thenAccept(System.out::println); // runs immediatelyManually Completing a Future
Use complete() to provide the result from outside the computation. Use completeExceptionally() to signal failure.
CompletableFuture<String> promise = new CompletableFuture<>();
// In another thread or callback:
promise.complete("done!"); // signals success
// promise.completeExceptionally(new RuntimeException("fail")); // signals failure
String result = promise.get(); // blocks until completedget() and join()
Both get() and join() block until the future completes. get() throws checked exceptions; join() wraps them in unchecked CompletionException.
try {
String r = future.get(5, TimeUnit.SECONDS); // checked exceptions
} catch (TimeoutException | InterruptedException | ExecutionException e) { ... }
// Or:
String r = future.join(); // throws CompletionException (unchecked)getNow() for Non-Blocking Check
getNow(defaultValue) returns the result if already completed, or the supplied default if not — non-blocking, no waiting.
String result = future.getNow("loading...");
System.out.println(result); // "loading..." if not yet doneisDone, isCancelled, isCompletedExceptionally
Check the state of a future without blocking. Combine these checks in polling loops or monitoring code.
if (future.isDone()) System.out.println("Completed");
if (future.isCancelled()) System.out.println("Cancelled");
if (future.isCompletedExceptionally()) System.out.println("Failed");cancel() for Timeout Handling
Call cancel(true) to cancel an in-progress computation. The future transitions to the cancelled state and any blocking get() throws CancellationException.
CompletableFuture<String> future = fetchAsync();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.schedule(() -> future.cancel(true), 3, TimeUnit.SECONDS);completeOnTimeout (Java 9+)
completeOnTimeout(value, timeout, unit) automatically completes the future with a default value if it has not completed within the timeout — cleaner than manual cancel.
CompletableFuture<String> result = fetchAsync()
.completeOnTimeout("default", 3, TimeUnit.SECONDS);
System.out.println(result.join()); // "default" if fetch took > 3sQuick Check
Which method starts an async computation on the common ForkJoinPool and returns a value?
Recap
supplyAsync / runAsync start async work. complete / completeExceptionally fulfill manually. Use join() for unchecked blocking. completeOnTimeout handles timeouts cleanly.
Frequently asked questions
Is the “Creating and Completing CompletableFutures” lesson free?
Yes — the full text of “Creating and Completing CompletableFutures” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Creating and Completing CompletableFutures”?
Use supplyAsync, runAsync, completedFuture, and manually complete futures with complete and completeExceptionally. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Creating and Completing CompletableFutures” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating and Completing CompletableFutures
- Chaining with thenApply and thenCompose
- Combining Futures: allOf and anyOf
- Error Handling and Async HTTP Pipeline