Package modernfeatures.concurrency
Class CompletableFutureBasicsExample
java.lang.Object
modernfeatures.concurrency.CompletableFutureBasicsExample
Demonstrates basic usage of CompletableFuture
for asynchronous programming in Java 8+.
- Run asynchronous tasks that return a result using
CompletableFuture.supplyAsync()
. - Run asynchronous tasks without a result using
CompletableFuture.runAsync()
. - Block and wait for asynchronous computations to complete using
get()
.
Example usage:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Long-running computation
Thread.sleep(10000);
return "Hello from CompletableFuture!";
});
String result = future.get();
System.out.println("Result: " + result);
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
CompletableFutureBasicsExample
public CompletableFutureBasicsExample()
-
-
Method Details
-
main
Main method demonstrating basic
CompletableFuture
usage.- Starts an asynchronous task that returns a result.
- Starts an asynchronous task without a result.
- Blocks the main thread to wait for completion of both tasks.
- Parameters:
args
- command line arguments (not used)- Throws:
ExecutionException
- if the computation threw an exceptionInterruptedException
- if the current thread was interrupted while waiting
-