CompletableFuture is a powerful tool in Java's concurrency framework that allows you to write asynchronous, non-blocking code. It represents a future result of an asynchronous computation, enabling you to handle tasks that complete at some point in the future. CompletableFuture makes it easy to run a task asynchronously and then combine the results of multiple tasks or handle exceptions, all while avoiding callback hell.
// Import the necessary packages
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
// Create a CompletableFuture that runs a task asynchronously
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
// Simulate a delay
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello from CompletableFuture!";
});
// Add a callback to handle the result
future.thenAccept(result -> {
System.out.println(result);
});
// Prevent main thread from exiting too soon
future.join();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?