如何使用CompletableFuture

本文详细介绍了Java中的CompletableFuture,包括它的概念、创建方式、获取任务结果的方法以及多种消费结果的方式,如whenComplete、thenAccept、thenApply等。此外,还探讨了多任务编排,如依赖、AND、OR关系以及并行任务的处理,并提供了RocketMQ中的实战代码示例。

目录

一、CompletableFuture是什么

二、CompletableFuture用法

2.1、创建CompletableFuture

2.1.1、直接创建

2.1.2、创建一个使用指定数据作为结果的已结束的CompletableFuture

 2.1.3、通过执行异步任务获取CompletableFuture

 2.2、获取任务结果

2.3、消费结果

2.3.1、whenComplete

2.3.2、thenAccept

2.3.3、thenApply

2.3.4、thenRun

2.3.5、handle

2.3.6、exceptionally

2.4、多任务编排

2.4.1、 依赖(thenCompose)

2.4.2、 AND(thenCombine,thenAcceptBoth,runAfterBoth)

2.4.3、OR(applyToEither)

2.4.4、 并行(allOf,anyOf)


一、CompletableFuture是什么

CompletableFuture是对Future的扩展和增强。CompletableFuture实现了Future接口和CompletionStage使其实现了对任务编排的能力,支持其在完成时触发相关功能或操作。借助这项能力,可以轻松地组织不同任务的运行顺序、规则以及方式。

二、CompletableFuture用法

2.1、创建CompletableFuture

2.1.1、直接创建

CompletableFuture completableFuture=new CompletableFuture();

2.1.2、创建一个使用指定数据作为结果的已结束的CompletableFuture

CompletableFuture<String> test1 = CompletableFuture.completedFuture("test");

 2.1.3、通过执行异步任务获取CompletableFuture

/**
 * 使用默认线程池执行异步任务,有返回值
 */
CompletableFuture.supplyAsync(() -> "hello CompletableFuture!");
/**
 * 使用指定线程池执行异步任务,有返回值
 */
CompletableFuture.supplyAsync(() -> "Hello CompletableFuture!", Executors.newCachedThreadPool());
/**
 * 使用默认线程池执行异步任务,无返回值
 */
CompletableFuture.runAsync(() -> System.out.println("Hello runAsync!"));
/**
  * 使用指定线程池执行异步任务,无返回值
  */
CompletableFuture.runAsync(() -> System.out.println("Hello RunAsync!"),  Executors.newCachedThreadPool());

 2.2、获取任务结果

方法 是否阻塞 是否抛出检查异常 说明
get() 阻塞 抛出检查异常
getNow(V value) 不阻塞 不抛出 如果任务没有结束就返回指定的默认值
get(long timeout, TimeUnit unit) 阻塞指定时间 抛出
join() 阻塞 不抛出

示例代码: 

        /**
         * 获取任务结果,阻塞直到任务结束,会抛出检查异常
         */
        String test = CompletableFuture.supplyAsync(() -> "Hello").get();
        /**
         * 获取任务结果,如果超过等待之间任务未结束则抛出TimeoutException
         */
        test = CompletableFuture.supplyAsync(() -> "test").get(10, TimeUnit.MILLISECONDS);
        /**
         * 如果任务结束则返回任务结果,如果任务未结束则返回指定的默认值
         */
        test = CompletableFuture.supplyAsync(() -> "test").getNow("default");

        /**
         * 阻塞获取任务结果,和get相似,但是不会抛出检查异常
         */
        test = CompletableFuture.supplyAsync(() -> "join").join();

2.3、消费结果

2.3.1、whenComplete

whenComplete是当某个任务执行完成后执行的回调方法,不管任务异常还是正常结束都会执行该回调;该回调的入参是任务的执行结果和异常;
如果是正常执行则异常为null,回调方法对应的CompletableFuture的result和该任务一致,如果该任务正常执行,则get方法返回执行结果,如果是执行异常,则get方法抛出异常。

方法 说明
 whenComplete(BiConsumer<? super T, ? super Throwable> action ) 在当前线程中同步执行回调操作
### CompletableFuture 实战用法与最佳实践 #### 什么是 CompletableFuture? `CompletableFuture` 是 Java 8 引入的一个类,用于支持异步编程。它扩展了 `Future` 接口的功能,提供了丰富的 API 来组合多个异步任务并处理它们的结果[^1]。 #### 如何使用 CompletableFuture? 以下是几个常见的实战场景以及对应的代码示例: --- #### 场景一:简单的异步任务 当需要执行一个独立的异步任务时,可以直接使用 `supplyAsync()` 或者 `runAsync()` 方法来启动任务。 ```java import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; public class SimpleTaskExample { public static void main(String[] args) throws ExecutionException, InterruptedException { // 创建一个返回字符串的任务 CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello CompletableFuture"); // 获取结果 String result = future.get(); System.out.println(result); } } ``` 上述代码展示了如何创建一个简单异步任务,并通过 `.get()` 方法阻塞等待其完成。 --- #### 场景二:链式调用优化代码可读性 通过链式调用的方式,可以让复杂的业务逻辑变得更加直观和简洁。例如,在一个任务完成后继续执行另一个任务。 ```java import java.util.concurrent.CompletableFuture; public class ChainCallExample { public static void main(String[] args) { CompletableFuture<Void> chain = CompletableFuture.supplyAsync(() -> "Data from Task A") .thenApply(data -> data.toUpperCase()) // 转换数据为大写 .thenAccept(System.out::println); // 打印转换后的数据 } } ``` 此例子说明了如何利用 `thenApply()` 对前一步骤的结果进行加工,并最终打印出来[^3]。 --- #### 场景三:任务间的依赖关系(Compose vs Combine) 如果某些任务之间存在依赖关系,则可以通过 `thenCompose()` 将两个任务串联起来;而如果是平行运行但需合并结果的情况则适合采用 `thenCombine()`。 ```java // thenCompose 示例 CompletableFuture<Integer> composedResult = CompletableFuture.supplyAsync(() -> 42) .thenCompose(number -> CompletableFuture.supplyAsync(() -> number * 2)); composedResult.thenAccept(System.out::println); // thenCombine 示例 CompletableFuture<String> combinedResult = CompletableFuture.supplyAsync(() -> "PartA") .thenCombine(CompletableFuture.supplyAsync(() -> "-PartB"), (a, b) -> a + b); combinedResult.thenAccept(System.out::println); ``` 这里分别演示了两种不同方式下如何管理相互关联或者无关却要共同作用的操作序列[^2]。 --- #### 场景四:异常处理机制 在实际开发过程中不可避免会遇到错误情况发生,因此合理设计好失败路径非常重要。 ```java import java.util.concurrent.CompletableFuture; public class ExceptionHandlingExample { public static void main(String[] args) { CompletableFuture<Void> handleFailure = CompletableFuture.supplyAsync(() -> { throw new RuntimeException("Something went wrong!"); }).exceptionally(ex -> { ex.printStackTrace(); return null; // 返回默认值或采取其他补救措施 }); handleFailure.join(); // 非阻塞地结束整个流程 } } ``` 这段程序片段表明即使上游抛出了未预期状况也能被妥善捕获而不至于崩溃整个应用流。 --- #### 场景五:多线程环境下的注意事项 需要注意的是,在高并发环境下如果不加以控制可能会引发资源竞争等问题。下面给出了一种改进方案避免此类风险。 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.CompletableFuture; public class ThreadManagementExample { private static final ExecutorService executor = Executors.newFixedThreadPool(5); public static void main(String[] args) throws InterruptedException { try { for(int i=0;i<10;i++) { CompletableFuture.supplyAsync(ThreadManagementExample::doWork,executor) .thenAccept(ThreadManagementExample::processResult); } Thread.sleep(2000L); // 给予足够时间让所有子任务完成 } finally{ executor.shutdownNow(); // 清理工作池防止内存泄漏 } } private static Object doWork(){ return Math.random()*100D; } private static void processResult(Object obj){ System.out.println("Processed Result:"+obj.toString()); } } ``` 该案例强调自定义线程池的重要性以确保性能稳定性和安全性[^4]。 --- #### 总结 综上所述,`CompletableFuture` 提供了一个强大灵活的工具集帮助开发者构建高效可靠的异步应用程序。然而为了充分发挥它的潜力还需要遵循一些基本原则比如保持良好的编码习惯、适当运用各种方法论以及密切关注潜在陷阱等等。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈脩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值