Concurrency
concurrency4CompletableFutureDemo
- Path
- pkg7concurrency/concurrency4CompletableFutureDemo.java
- Package
- pkg7concurrency
- Study order
- 4
- Run
- Single-file source launch
- Command
- java pkg7concurrency/concurrency4CompletableFutureDemo.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg7concurrency;2 3/*4 * concurrency4CompletableFutureDemo.java5 * --------------------------6 * Asynchronous pipelines: chain, combine, and handle errors without blocking.7 *8 * KEY METHODS:9 * supplyAsync / runAsync : start async work.10 * thenApply / thenCompose : transform / flat-map the result.11 * thenCombine : combine two independent futures.12 * exceptionally / handle : recover from failures.13 * allOf / anyOf : coordinate multiple futures.14 */15import java.util.concurrent.*;16 17public class concurrency4CompletableFutureDemo {18 19 static int slow(int x) {20 try { Thread.sleep(30); } catch (InterruptedException ignored) {}21 return x;22 }23 24 public static void main(String[] args) throws Exception {25 // Chain transformations26 CompletableFuture<String> pipeline = CompletableFuture27 .supplyAsync(() -> slow(10))28 .thenApply(x -> x * 2) // 2029 .thenApply(x -> "result=" + x);30 System.out.println(pipeline.get());31 32 // thenCompose: dependent async step (flat-map)33 CompletableFuture<Integer> composed = CompletableFuture34 .supplyAsync(() -> slow(5))35 .thenCompose(x -> CompletableFuture.supplyAsync(() -> x + 100));36 System.out.println("composed: " + composed.get());37 38 // thenCombine: merge two independent computations39 CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> slow(3));40 CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> slow(4));41 System.out.println("combined a+b: " + a.thenCombine(b, Integer::sum).get());42 43 // Error handling44 CompletableFuture<Integer> recovered = CompletableFuture45 .<Integer>supplyAsync(() -> { throw new RuntimeException("boom"); })46 .exceptionally(ex -> { System.out.println("recovered from: " + ex.getMessage()); return -1; });47 System.out.println("recovered value: " + recovered.get());48 49 // allOf: wait for many50 CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> slow(1));51 CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> slow(2));52 CompletableFuture.allOf(f1, f2).join();53 System.out.println("allOf done: " + f1.get() + ", " + f2.get());54 }55}