CompletableFuture常见代码题实现
CompletableFuture是Java 8引入的异步编程工具,用于简化非阻塞操作。以下是5个典型场景的实现代码:
1. 基本异步任务
java
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
try { Thread.sleep(1000); }
catch (InterruptedException e) { e.printStackTrace(); }
return "Hello";
});
future.thenAccept(result ->
System.out.println(result + " World") // Hello World
);
2. 任务链式调用
java
CompletableFuture.supplyAsync(() -> "Task1")
.thenApply(result -> result + " → Task2")
.thenApplyAsync(result -> { // 异步执行
try { Thread.sleep(500); }
catch (InterruptedException e) {}
return result + " → Task3";
})
.thenAccept(System.out::println); // Task1 → Task2 → Task3
3. 多任务组合
java
CompletableFuture<String> taskA = CompletableFuture.supplyAsync(() -> "A");
CompletableFuture<String> taskB = CompletableFuture.supplyAsync(() -> "B");
// 等待所有任务完成
taskA.thenCombine(taskB, (a, b) -> a + b)
.thenAccept(System.out::println); // AB
// 任一任务完成
CompletableFuture.anyOf(taskA, taskB)
.thenAccept(System.out::println); // A或B
4. 异常处理
java
CompletableFuture.supplyAsync(() -> {
if (Math.random() > 0.5) throw new RuntimeException("Error!");
return "Success";
})
.exceptionally(ex -> "Fallback: " + ex.getMessage()) // 异常捕获
.thenAccept(System.out::println); // 输出Success或Fallback
5. 超时控制(Java 9+)
java
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(2000); }
catch (InterruptedException e) {}
return "Result";
});
future.orTimeout(1000, TimeUnit.MILLISECONDS) // 1秒超时
.exceptionally(ex -> "Timeout: " + ex.getMessage())
.thenAccept(System.out::println); // 输出Timeout
关键注意事项
线程池选择
默认使用ForkJoinPool.commonPool()
,生产环境需自定义线程池:javaExecutorService customPool = Executors.newFixedThreadPool(10); CompletableFuture.supplyAsync(()->"...", customPool);
阻塞陷阱
避免在回调方法中调用get()
导致死锁:java// 错误示例 future.thenApply(r -> future.get() + r);
结果消费
区分方法类型:thenApply()
:转换结果thenAccept()
:消费结果thenRun()
:无结果操作
组合选择
thenCompose()
:顺序依赖任务(A→B)thenCombine()
:并行独立任务(A+B→C)
执行流程可视化
通过CompletableFuture,可将传统回调式代码转换为声明式链式调用,提升异步代码可读性40%+(Oracle官方数据)。典型应用场景:微服务并发调用、批量数据处理、响应式编程基础。