CompletableFuture 是 Java 8 引入的异步编程工具,通过链式调用和非阻塞操作简化多线程任务编排。
创建异步任务
1.带返回值的任务
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
2. 无返回值的任务
使用 runAsync(),适用于仅执行操作的场景:
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("Running"));
3. 自定义线程池
默认使用 ForkJoinPool.commonPool(),可通过参数指定自定义线程池优化资源管理:
这里可以结合spring 定义全局线程池来实现统一管理, 使用时将容器中的executor当做入参即可
ExecutorService executor = Executors.newCachedThreadPool();
CompletableFuture.supplyAsync(() -> "Task", executor);
链式调用与任务组合
1. 结果转换
thenApply():将前序结果转换为新值:
future.thenApply(s -> s + " World"); // "Hello" → "Hello World"
2. 结果消费
thenAccept():仅消费结果不返回新值:
future.thenAccept(System.out::println); // 输出结果
3. 任务串联
thenCompose():将前序结果作为新异步任务的输入:
future.thenCompose(s -> CompletableFuture.supplyAsync(() -> s.length()));
4. 并行合并结果
thenCombine():合并两个独立任务的结果:
future1.thenCombine(future2, (res1, res2) -> res1 + res2);
5. 多任务协同
allOf():等待所有任务完成;
anyOf():等待任一任务完成。
CompletableFuture.allOf(future1, future2).thenRun(() -> System.out.println("All done"));
异常处理
捕获异常并返回默认值
exceptionally():在异常时提供兜底结果:
future.exceptionally(ex -> "Fallback");
统一处理结果与异常
handle():无论成功或失败均执行操作:
future.handle((res, ex) -> ex != null ? "Error" : res);
超时控制
使用 orTimeout() 设置任务超时,超时后抛出 TimeoutException:
CompletableFuture.supplyAsync(() -> "Task").orTimeout(500, TimeUnit.MILLISECONDS).exceptionally(ex -> "Timeout: " + ex.getMessage());