Java Completable Futures and Threads Flashcards
https://hatchjs.com/future-vs-completablefuture-java-8/ https://www.callicoder.com/java-8-completablefuture-tutorial/
Completable Future
CompletableFuture is a class introduced in Java 8 that allows us to write asynchronous, non-blocking code
Completable Future Example
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello, world!";
});</String>
future.thenAccept(result -> System.out.println(result));
We’re then calling the thenAccept() method on the CompletableFuture object to specify what to do when the operation is complete.
Chaining async operations
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 10)
.thenApplyAsync(result -> result * 2)
.thenApplyAsync(result -> result + 5);</Integer>
future.thenAccept(result -> System.out.println(result));
Completable Future - Blocking vs Non Blocking
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> longRunningCall());
future.thenAccept(result -> System.out.println("Got: " + result));
The main thread does no wait. When the long running task completes the call back of thenAccept is loaded onto the call stack
But if you do future.get(); The main thread blocks till the asyn code returns the value.</String>
Handling Exception - with exceptionally
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
if (true) throw new RuntimeException("Boom!");
return "Hello";
}).exceptionally(ex -> {
System.out.println("Caught exception: " + ex.getMessage());
return "Fallback value";
});</String>
Handling Exceptions - with handle
handle() is more powerful — it gives you both the result and the exception, and lets you return a new value either way.
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Oops");
}).handle((result, ex) -> {
if (ex != null) {
System.out.println("Handled exception: " + ex.getMessage());
return "Recovered";
}
return result;
});</String>
Tip - Exception Handling
Always end chains with an exception handler
runAsync with executor
ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture.runAsync(() -> {
// Your logic here
}, executor);
Without executor, ForkJoinPool.commonPool() default exectutor is used
Limited threads → usually availableProcessors() - 1
Shared across the JVM