supplyAsync and runAsync
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every CompletableFuture pipeline starts with a task running somewhere. supplyAsync starts a task that returns a value and runAsync starts one that returns nothing; both hand you a future at once.
Starting work in the background
supplyAsync is a static CompletableFuture method that runs a Supplier on a background thread and returns a CompletableFuture that will hold the value the supplier returns.
CompletableFuture.supplyAsync(supplier) runs a Supplier<T> on a background thread and returns a CompletableFuture<T> that will hold its result. runAsync(runnable) does the same for a Runnable, which returns nothing, so its future is a CompletableFuture<Void>.
Example 1 · supplyAsync returns a value, runAsync does not
import java.util.concurrent.CompletableFuture;
public class StartAsyncDemo { static String pnrStatus(String pnr) { sleep(150); // slow railway server return "PNR " + pnr + ": RAC 12"; }
static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) { CompletableFuture<String> status = CompletableFuture.supplyAsync(() -> pnrStatus("4521897630")); CompletableFuture<Void> audit = CompletableFuture.runAsync(() -> { sleep(50); System.out.println("Audit log written"); }); System.out.println("Both tasks started");
System.out.println("audit.join() returned: " + audit.join()); System.out.println(status.join()); }}Both tasks started Audit log written audit.join() returned: null PNR 4521897630: RAC 12
What this code does
- Both calls return at once, so
Both tasks startedprints first while the two tasks run in the background. auditis aCompletableFuture<Void>: itsjoin()waits for the task and returnsnull.status.join()returns theStringthe supplier produced.
Both methods return straight away. The task runs on another thread while the caller carries on. For a Void future, join() returns null: the future only tells you when the task finished. A Supplier takes no input and returns a value: () -> pnrStatus(pnr). A Runnable takes no input and returns nothing: () -> writeAuditLog().
Supplier.get() and Runnable.run() cannot throw checked exceptions. If the work can throw IOException, catch it inside the lambda and rethrow it as an unchecked exception such as UncheckedIOException.The common ForkJoinPool
When you pass no executor, the task runs in the common pool, ForkJoinPool.commonPool(): one shared pool of threads that the JVM creates for the whole program. Parallel streams use the same pool.
Example 2 · Where the task runs: the common pool
import java.util.concurrent.CompletableFuture;import java.util.concurrent.ForkJoinPool;
public class CommonPoolDemo { public static void main(String[] args) { CompletableFuture<String> where = CompletableFuture.supplyAsync(() -> { Thread t = Thread.currentThread(); return "common pool thread: " + t.getName().startsWith("ForkJoinPool.commonPool-worker") + ", daemon: " + t.isDaemon(); });
System.out.println("main runs on: " + Thread.currentThread().getName()); System.out.println(where.join());
int cores = Runtime.getRuntime().availableProcessors(); int size = ForkJoinPool.commonPool().getParallelism(); System.out.println("pool size is cores - 1: " + (size == Math.max(1, cores - 1))); }}main runs on: main common pool thread: true, daemon: true pool size is cores - 1: true
What this code does
- The supplier runs on a thread named like
ForkJoinPool.commonPool-worker-3(the number changes), and that thread is a daemon thread. - This output is for a machine with 3 or more cores and default settings. With 1 or 2 cores, each task gets its own new thread instead, so the first check prints
false.
By default its size is one less than the number of CPU cores, so 7 threads on an 8-core laptop. Its threads are daemon threads: background threads that do not keep the JVM alive. On a machine with only 1 or 2 cores the pool would be too small, so CompletableFuture starts a new thread for each task instead. Lesson 7 of this module shows how to pass your own executor.
join() versus get()
join() waits for the result and returns it; if the task failed, it throws an unchecked CompletionException with the real error as its cause. get() comes from Future: it waits the same way, but throws the checked exceptions InterruptedException and ExecutionException.
Example 3 · join and get when the task fails
import java.util.concurrent.CompletableFuture;import java.util.concurrent.CompletionException;import java.util.concurrent.ExecutionException;
public class JoinVersusGetDemo { static int fetchSeats(String train) { if (train.isEmpty()) { throw new IllegalArgumentException("train number missing"); } return 23; }
public static void main(String[] args) { CompletableFuture<Integer> ok = CompletableFuture.supplyAsync(() -> fetchSeats("12627")); System.out.println("join: " + ok.join() + " seats");
CompletableFuture<Integer> bad = CompletableFuture.supplyAsync(() -> fetchSeats("")); try { bad.join(); } catch (CompletionException e) { System.out.println("join threw CompletionException, cause: " + e.getCause()); }
try { bad.get(); } catch (InterruptedException | ExecutionException e) { System.out.println("get threw " + e.getClass().getSimpleName() + ", cause: " + e.getCause()); } }}join: 23 seats join threw CompletionException, cause: java.lang.IllegalArgumentException: train number missing get threw ExecutionException, cause: java.lang.IllegalArgumentException: train number missing
What this code does
- The exception thrown inside the supplier is stored in the future.
join()rethrows it wrapped in aCompletionException;get()wraps it in anExecutionException. - In both cases
getCause()gives back the realIllegalArgumentException. Onlyget()forces thetry/catchon you, because its exceptions are checked.
Example 4 · get with a time limit, and getNow
import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class WaitWithLimitDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) throws Exception { CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> { sleep(200); // busy result server return "PASS, 8.4 CGPA"; });
System.out.println("getNow: " + result.getNow("still processing")); try { result.get(50, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { System.out.println("get gave up after 50 ms, task done? " + result.isDone()); }
System.out.println("join: " + result.join()); System.out.println("getNow: " + result.getNow("still processing")); }}getNow: still processing get gave up after 50 ms, task done? false join: PASS, 8.4 CGPA getNow: PASS, 8.4 CGPA
What this code does
getNownever waits: before the task ends it returns the default you gave, afterwards the real result.get(50, TimeUnit.MILLISECONDS)stops waiting with aTimeoutException, but it does not stop the task. That is why the laterjoin()still gets the result.
join(): waits; failure becomesCompletionException(unchecked).get(): waits; failure becomesExecutionException(checked), and you must handleInterruptedException.get(50, TimeUnit.MILLISECONDS): waits at most 50 ms, then throwsTimeoutException. The task keeps running.getNow(valueIfAbsent): never waits; returns the result if done, otherwise your default.
Because join() throws nothing checked, it fits inside lambdas and streams without a try. Use get() when you need its extra form, get(timeout, unit), which gives up waiting after a time limit.
Why main may exit before the work prints
The JVM exits when only daemon threads are left. Common pool threads are daemon threads, so when main ends, any unfinished async work is dropped without a message.
Example 5 · Bug: main ends before the SMS is sent
import java.util.concurrent.CompletableFuture;
public class EarlyExitDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) { CompletableFuture.runAsync(() -> { sleep(200); // talking to the SMS gateway System.out.println("SMS sent: your order is confirmed"); }); System.out.println("main finished"); }}main finished
What this code does
mainreturns after about a millisecond. The only thread left is a daemon common pool thread, so the JVM exits and the SMS line almost never appears.- Timing decides this, which is why the output is a sample: on a very slow start-up the line could still slip out. Never rely on luck here.
Example 6 · Fix: keep the future and join it
import java.util.concurrent.CompletableFuture;
public class JoinBeforeExitDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) { CompletableFuture<Void> sms = CompletableFuture.runAsync(() -> { sleep(200); // talking to the SMS gateway System.out.println("SMS sent: your order is confirmed"); }); System.out.println("main: waiting for the SMS task");
sms.join(); System.out.println("main finished"); }}main: waiting for the SMS task SMS sent: your order is confirmed main finished
What this code does
- The future returned by
runAsyncis now stored insms, andsms.join()keepsmainalive until the task has printed its line. - The order is fixed:
mainprints first, the SMS line comes about 200 ms later, andmain finishedcomes last.
This is the most common surprise with CompletableFuture: the program runs, prints main finished, and the background step never appears. Nothing is wrong with the task; the JVM simply stopped before it ran. The fix is to keep the future and join() it before main returns. In a web server the JVM keeps running anyway, so there you usually do not block at all.
Next step
Check your understanding
12 quick questions