Appearance
CompletableFuture 常用 API 总结
CompletableFuture 是 Java 8 引入的一个强大的异步编程工具,提供了丰富的 API 来处理异步操作。以下是主要的 API 分类:
1. 创建 CompletableFuture
CompletableFuture.supplyAsync(Supplier<U> supplier)- 异步执行 Supplier 并返回结果CompletableFuture.supplyAsync(Supplier<U> supplier, Executor executor)- 使用指定线程池执行CompletableFuture.runAsync(Runnable runnable)- 异步执行 RunnableCompletableFuture.runAsync(Runnable runnable, Executor executor)- 使用指定线程池执行CompletableFuture.completedFuture(U value)- 创建一个已完成的 Future
2. 结果处理
thenApply(Function<? super T,? extends U> fn)- 对结果应用函数thenAccept(Consumer<? super T> action)- 消费结果但不返回新值thenRun(Runnable action)- 结果可用后执行 RunnablethenCompose(Function<? super T,? extends CompletionStage<U>> fn)- 扁平化处理(类似 flatMap)
3. 组合多个 Future
thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)- 合并两个 Future 的结果thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)- 合并并消费两个结果runAfterBoth(CompletionStage<?> other, Runnable action)- 两个都完成后执行 RunnableapplyToEither(CompletionStage<? extends T> other, Function<? super T, U> fn)- 使用第一个完成的结果acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)- 消费第一个完成的结果runAfterEither(CompletionStage<?> other, Runnable action)- 任一完成后执行 RunnableallOf(CompletableFuture<?>... cfs)- 所有 Future 完成后完成anyOf(CompletableFuture<?>... cfs)- 任一 Future 完成后完成
4. 异常处理
exceptionally(Function<Throwable,? extends T> fn)- 处理异常并返回替代值handle(BiFunction<? super T, Throwable, ? extends U> fn)- 无论成功或失败都处理whenComplete(BiConsumer<? super T, ? super Throwable> action)- 无论成功或失败都执行,但不改变结果
5. 完成控制
complete(T value)- 手动完成 FuturecompleteExceptionally(Throwable ex)- 手动以异常完成 Futurecancel(boolean mayInterruptIfRunning)- 取消 FutureobtrudeValue(T value)- 强制设置结果(即使已完成)obtrudeException(Throwable ex)- 强制设置异常(即使已完成)
6. 获取结果
get()- 阻塞获取结果get(long timeout, TimeUnit unit)- 带超时的阻塞获取join()- 类似 get() 但不抛出检查异常getNow(T valueIfAbsent)- 立即获取结果或返回默认值isDone()- 检查是否完成isCompletedExceptionally()- 检查是否异常完成isCancelled()- 检查是否已取消
7. 其他实用方法
orTimeout(long timeout, TimeUnit unit)- 设置超时时间completeOnTimeout(T value, long timeout, TimeUnit unit)- 超时后使用默认值完成toCompletableFuture()- 返回自身(用于 CompletionStage 接口)defaultExecutor()- 获取默认执行器minimalCompletionStage()- 返回最小化的 CompletionStage
CompletableFuture 的这些 API 可以组合使用,构建复杂的异步处理流程,大大简化了异步编程的复杂性。