Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

CompletableFuture.join(): retrieving the result

`join()` retrieves a `CompletableFuture` result, waiting for completion if necessary. It declares no checked exceptions, but it can still throw an unchecked exception.

Version: Java SE 21

Syntax

public T join()

In Java SE 21, CompletableFuture.join() is a no-argument instance method of java.util.concurrent.CompletableFuture<T>. If the future is incomplete, the call blocks the current thread until it completes. On normal completion, it returns the result of type T; if the result is already available, there is no wait.

If the computation fails, join() throws CompletionException, and you can inspect its cause with getCause(). If the future itself was cancelled, join() throws CancellationException directly. Both exceptions are unchecked: the compiler does not require you to catch or declare them.

Unlike join(), get() throws the checked InterruptedException if the wait is interrupted and reports computation failure with the checked ExecutionException. join() does not end the wait by throwing InterruptedException and takes no timeout; use get(timeout, unit) for a bounded wait. Thread.join() instead waits for a thread to terminate, returns no computation result (void), and declares InterruptedException.

Examples

import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

public class Main {
    public static void main(String[] args) {
        CompletableFuture<Integer> success = CompletableFuture.completedFuture(42);
        System.out.println(success.join());

        CompletableFuture<Integer> failure =
                CompletableFuture.failedFuture(new IllegalArgumentException("invalid input"));
        try {
            failure.join();
        } catch (CompletionException e) {
            System.out.println("failure: " + e.getCause().getMessage());
        }

        CompletableFuture<Integer> cancelled = new CompletableFuture<>();
        cancelled.cancel(false);
        try {
            cancelled.join();
        } catch (CancellationException e) {
            System.out.println("cancelled");
        }
    }
}

Result

42
failure: invalid input
cancelled

Each future is already complete before `join()` is called. The example shows the value `42`, the message from the failure's cause, and a directly thrown `CancellationException`; it does not demonstrate blocking.

Related lessons

  • Java · Lesson 51 · Intermediate · Version: 2

Sources