Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
import java.util.concurrent.*; import java.util.List; public class CompletableFutureDemo { static String fetchUser(int id) throws InterruptedException { Thread.sleep(100); // simulate network return "User#" + id; } static String fetchEmail(String user) throws InterruptedException { Thread.sleep(80); return user.toLowerCase().replace("#", "") + "@example.com"; } public static void main(String[] args) throws Exception { // Basic async computation CompletableFuture<String> future = CompletableFuture .supplyAsync(() -> { try { return fetchUser(42); } catch (InterruptedException e) { throw new RuntimeException(e); } }) .thenApply(user -> user + " (verified)") .thenApply(String::toUpperCase); System.out.println("Result: " + future.get()); // thenCompose: chain dependent async calls CompletableFuture<String> emailFuture = CompletableFuture .supplyAsync(() -> { try { return fetchUser(7); } catch (InterruptedException e) { throw new RuntimeException(e); } }) .thenCompose(user -> CompletableFuture.supplyAsync(() -> { try { return fetchEmail(user); } catch (InterruptedException e) { throw new RuntimeException(e); } })); System.out.println("Email: " + emailFuture.get()); // allOf: wait for multiple futures var f1 = CompletableFuture.supplyAsync(() -> "Result A"); var f2 = CompletableFuture.supplyAsync(() -> "Result B"); var f3 = CompletableFuture.supplyAsync(() -> "Result C"); CompletableFuture.allOf(f1, f2, f3).join(); System.out.println(f1.get() + ", " + f2.get() + ", " + f3.get()); // exceptionally: fallback on failure CompletableFuture<String> safe = CompletableFuture .supplyAsync(() -> { throw new RuntimeException("network error"); }) .exceptionally(ex -> "Fallback: " + ex.getMessage()); System.out.println(safe.get()); } }
Result
Open