CompletableFuture异步编排详解
请说明CompletableFuture的核心API:thenApply/thenCompose/allOf/anyOf的区别和用法,以及如何实现异步任务编排。
回答
孤独的心
CompletableFuture是JDK8引入的异步编程工具,支持函数式组合。
核心API:
- thenApply(Function):对结果进行转换,返回CompletableFuture(同步映射)。
- thenCompose(Function):将CompletableFuture扁平化,避免嵌套(异步flatMap)。
- allOf(CompletableFuture...):等待所有任务完成,无返回值。
- anyOf(CompletableFuture...):任意一个任务完成即返回。
其他重要API:
- exceptionally:异常恢复。
- thenCombine:合并两个CF的结果。
- thenAccept:消费结果。
- handle:处理结果和异常。
注意:默认使用ForkJoinPool.commonPool(),可指定自定义线程池。