Completable Futures
CompletableFuture is a class introduced in Java 8 to support asynchronous and concurrent programming. It represents a computation that may or may not have completed yet and provides a way to chain dependent computations, handle exceptions, and compose multiple CompletableFuture instances.
Creating a CompletableFuture
To create a CompletableFuture, you can use the CompletableFuture constructor, which creates an incomplete CompletableFuture that can be completed manually later. Here's an example:
TEXT/X-JAVA
1CompletableFuture<String> completableFuture = new CompletableFuture<>();
xxxxxxxxxx
29
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
// Create a CompletableFuture
CompletableFuture<String> completableFuture = new CompletableFuture<>();
// Perform some async task
new Thread(() -> {
try {
// Simulate a long-running task
Thread.sleep(2000);
// Complete the CompletableFuture with a result
completableFuture.complete("Async task completed!");
} catch (InterruptedException e) {
// Handle any exceptions
completableFuture.completeExceptionally(e);
}
}).start();
// Get the result from the CompletableFuture
completableFuture.thenAccept(result -> {
System.out.println(result);
});
System.out.println("Waiting for async task to complete...");
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment