Skip to content

Commit f66098d

Browse files
committed
Add CompletableFutureExample and SupplyAsyncExampleOne classes to demonstrate CompletableFuture usage
1 parent 84da5f8 commit f66098d

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.java8;
2+
3+
public class SupplyAsyncExampleOne {
4+
public static void main(String[] args) {
5+
6+
}
7+
}

0 commit comments

Comments
 (0)