Java SE API
CompletableFuture.supplyAsync(Supplier, Executor)
Submit a supplier using an explicit executor.
Formal Syntax & Structure
java syntaxjava
static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| supplier | Supplier<U> | Value-producing operation |
| executor | Executor | Execution facility |
Working Example
Example Snippetjava
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main { static ThreadPoolExecutor pool(int workers, int capacity) { return new ThreadPoolExecutor(workers, workers, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(capacity), new ThreadPoolExecutor.AbortPolicy()); } static void stop(ExecutorService pool) throws InterruptedException { pool.shutdown(); try { if (!pool.awaitTermination(3, TimeUnit.SECONDS)) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } if (!pool.awaitTermination(3, TimeUnit.SECONDS)) throw new AssertionError("workers still running"); } } catch (InterruptedException e) { for (Runnable pending : pool.shutdownNow()) { if (pending instanceof Future<?> future) future.cancel(false); } throw e; } }
static CompletableFuture<Integer> quote(Executor executor) { return CompletableFuture.supplyAsync(() -> 6, executor) .thenCompose(n -> CompletableFuture.supplyAsync(() -> n * 7, executor)); } public static void main(String[] args) throws Exception { ThreadPoolExecutor workers = pool(1, 2); try { CompletableFuture<Integer> total = quote(workers); System.out.println(total.get(3, TimeUnit.SECONDS)); } finally { stop(workers); } System.out.println(workers.isTerminated()); }}