File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .java8 ;
2+
3+ import java .util .concurrent .CompletableFuture ;
4+
5+ /**
6+ * Demonstrates simple usages of CompletableFuture: supplyAsync and runAsync.
7+ * <p>
8+ * supplyAsync: runs a Supplier that produces a result and returns a
9+ * CompletableFuture<T>. The example calls join() to wait for the result.
10+ * <p>
11+ * runAsync: runs a Runnable that does not produce a result and returns a
12+ * CompletableFuture<Void>. Because runAsync is non-blocking, the program may
13+ * exit before the task completes unless the future is awaited (e.g., join()).
14+ */
15+ public class CompletableFutureExample {
16+ public static void main (String [] args ) {
17+ // supplyAsync(): accepts a Supplier<T> and runs it asynchronously (by default
18+ // using the ForkJoinPool.commonPool()). It returns a CompletableFuture<T>
19+ // that will complete with the supplier's result. Calling join() blocks the
20+ // current thread until the result is available (and will rethrow exceptions).
21+ CompletableFuture <String > supplyAsyncFuture = CompletableFuture .supplyAsync (() -> "Hello supplyAsync World!" );
22+ System .out .println (supplyAsyncFuture .join ());
23+ // runAsync(): accepts a Runnable and runs it asynchronously, returning a
24+ // CompletableFuture<Void>. Because it doesn't produce a value, you must
25+ // still wait on the returned future (e.g., join()) if you need to ensure
26+ // the task completes before program exit.
27+ CompletableFuture <Void > runAsyncFuture = CompletableFuture .runAsync (() -> System .out .println ("Hello runAsync World!" ));
28+ runAsyncFuture .join ();
29+ }
30+ }
Original file line number Diff line number Diff line change 1+ package com .java8 ;
2+
3+ public class SupplyAsyncExampleOne {
4+ public static void main (String [] args ) {
5+
6+ }
7+ }
You can’t perform that action at this time.
0 commit comments