Sub topic 3
Getting the result: join versus get
CompletableFuture lets you describe work without waiting for it. At some point, though, a thread usually needs the value, for example main before it prints, or a test before it asserts. This chapter covers the methods that block for a result, how they differ, and when to avoid them.
This chapter assumes you know lambdas, ExecutorService basics, and the difference between checked and unchecked exceptions. It also assumes you have seen supplyAsync and thenApply from the earlier chapters.
The two blocking methods
Both get() and join() block the calling thread until the future completes, then return the value. For a successful future they give the same answer.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class GetVsJoin {
public static void main(String[] args)
throws InterruptedException, ExecutionException {
CompletableFuture<String> future =
CompletableFuture.supplyAsync(() -> "ready");
System.out.println(future.get());
System.out.println(future.join());
}
}This prints ready twice. Once a future has completed, calling either method again returns immediately with the same stored result.
The two methods differ in where they come from and in how they report problems:
get()is declared by thejava.util.concurrent.Futureinterface. It declares the checked exceptionsInterruptedExceptionandExecutionException.join()is defined only onCompletableFuture(andCompletionStageimplementations such asForkJoinTaskdo not share it). It declares no checked exceptions.
That difference in signatures drives most of the practical advice below.
How failures are reported
A future can finish in one of three ways: with a value, with an exception, or by being cancelled. The table shows what each method does in each case.
| Outcome of the future | `get()` | `join()` |
|---|---|---|
| Completed with a value | Returns the value | Returns the value |
| Failed with exception `X` | Throws `ExecutionException` whose cause is `X` | Throws `CompletionException` whose cause is `X` |
| Cancelled | Throws `CancellationException` | Throws `CancellationException` |
| Waiting thread interrupted | Throws `InterruptedException` | Keeps waiting |
The code below shows the wrapping on a task that fails.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
public class WrappingDemo {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<Integer> failing = CompletableFuture
.supplyAsync(() -> Integer.parseInt("abc"));
try {
failing.get();
} catch (ExecutionException e) {
System.out.println("get cause: " + e.getCause());
}
try {
failing.join();
} catch (CompletionException e) {
System.out.println("join cause: " + e.getCause());
}
}
}Both lines report the same NumberFormatException. The wrapper type is the only difference. In both cases the exception your code threw is available through getCause(), so a catch block that checks e.getMessage() of the wrapper will see something like java.lang.NumberFormatException: ... rather than your original message. Always read the cause.
Why two wrapper types exist
ExecutionException is the checked exception that the old Future contract requires. CompletionException is its unchecked counterpart, introduced for CompletableFuture so that exceptions can travel through a chain of stages without checked-exception declarations. When one stage fails, every dependent stage also completes exceptionally, and the failure arrives wrapped in a CompletionException.
If you call get() on such a dependent stage, the implementation unwraps the CompletionException and rewraps its cause in an ExecutionException. You never see a CompletionException as the cause of an ExecutionException from get(). If you call join(), a CompletionException is thrown as is. If the future was failed directly with completeExceptionally(ex), join() creates a new CompletionException around ex.
The same wrapping shows up inside exceptionally and handle, and the error-handling chapter covers it. The point to remember here is that the original exception is always the cause.
Choosing between get and join
Use this as a working rule:
- Use
join()inside lambdas, streams, and code that you do not want cluttered withtry/catchfor checked exceptions. - Use
get()when you need a timeout (get(long, TimeUnit)), or when the calling thread must react to interruption, for example in a worker that supports shutdown.
The checked exceptions of get() make it awkward in a stream pipeline, because lambdas passed to map cannot throw checked exceptions. The allOf example in the spine uses CompletableFuture::join for exactly this reason. Writing the same step with get() would force a try/catch inside the lambda.
Interruption
A thread blocked in get() can be interrupted. When another thread calls interrupt() on it, get() throws InterruptedException. The correct response is to restore the flag or stop work, not to swallow the exception:
try {
String value = future.get();
// use value
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return; // stop what we were doing
} catch (ExecutionException e) {
// handle e.getCause()
}A thread blocked in join() does not stop waiting when interrupted. It keeps waiting for the result and leaves its interrupt status set afterwards. That makes join() a poor choice in code that must shut down promptly.
Waiting with a timeout
Only get has a timed form. It throws TimeoutException, a checked exception, if the time runs out.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class GetTimeout {
public static void main(String[] args)
throws InterruptedException, ExecutionException {
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "slow result";
});
try {
System.out.println(slow.get(200, TimeUnit.MILLISECONDS));
} catch (TimeoutException e) {
System.out.println("timed out, still running: " + !slow.isDone());
}
System.out.println(slow.getNow("not ready"));
}
}The output is timed out, still running: true, then not ready.
A timeout on get only stops the caller from waiting. It does not cancel the future and does not stop the task. The task keeps running on its pool thread and its result is simply ignored. If you want the future itself to fail or complete with a default after a deadline, use orTimeout or completeOnTimeout (Java 9 and later), covered in the timeouts chapter.
Checking without blocking
Sometimes you want the value only if it is already there. These methods never wait:
getNow(T valueIfAbsent)returns the result if the future is complete, otherwise the default you pass. If the future failed, it throwsCompletionExceptionlikejoin().isDone()istruefor any finished future, whether it succeeded, failed, or was cancelled.isCompletedExceptionally()istrueif it failed or was cancelled.isCancelled()istrueonly for cancellation.
Because isDone() is also true for failures, if (f.isDone()) f.join() can still throw. On Java 19 and later, Future also offers resultNow(), exceptionNow(), and state() for inspecting a finished future without a wrapper exception. On earlier versions, combine the checks above.
Wrapping join for cleaner callers
Callers often want the original unchecked exception, not a CompletionException. A small helper does the unwrapping once:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class Await {
static <T> T await(CompletableFuture<T> future) {
try {
return future.join();
} catch (CompletionException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
throw e; // a checked exception: keep the wrapper
}
}
public static void main(String[] args) {
CompletableFuture<Integer> failing = CompletableFuture.<Integer>supplyAsync(
() -> { throw new IllegalStateException("boom"); });
try {
await(failing);
} catch (IllegalStateException e) {
System.out.println("caught " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
}
}This prints caught IllegalStateException: boom. The stack trace of the rethrown exception still points at the worker thread where it was created, which is useful when debugging.
When not to block at all
Blocking defeats the main benefit of CompletableFuture. Each blocked thread is a thread that cannot do other work. Two situations deserve particular care.
- Blocking inside a task on the common pool. If a
supplyAsynclambda callsjoin()on another future that also needs a common-pool thread, tasks can wait on each other and exhaust the pool. The JDK may add compensating threads when aForkJoinPoolworker blocks injoinorget, but the compensation is limited and you should not design around it. UsethenComposeto express the dependency instead. - Blocking in the middle of a chain. Writing
a.thenApply(x -> b(x).join())turns an asynchronous pipeline back into a synchronous one. Return the future from the step and usethenCompose.
Quick reference
| Need | Use |
|---|---|
| Value in a lambda or stream | `join()` |
| Bounded wait | `get(timeout, unit)` |
| Responds to interrupt | `get()` |
| Value only if already available | `getNow(default)` |
| Original exception, unchecked | `join()` plus `getCause()` |
Exercise
A supplier passed to supplyAsync throws IllegalArgumentException. You call join() on the resulting future inside a try block. Which exception type do you catch, and how do you read the IllegalArgumentException? What type would get() throw instead?
Show answer
join() throws CompletionException, and you read the original with getCause(), which returns the IllegalArgumentException. get() would throw ExecutionException, which also exposes the original through getCause(). In both cases catching the wrapper and inspecting the cause is the reliable approach.
Exercise
You call future.get(1, TimeUnit.SECONDS) and receive a TimeoutException. Is the underlying task cancelled? What would you do if you wanted the future to finish with the string "default" after one second instead?
Show answer
No. The timeout only stops the caller from waiting, and the task keeps running with its result ignored. To give the future itself a fallback after a deadline, apply completeOnTimeout("default", 1, TimeUnit.SECONDS) to it on Java 9 or later, then call join().