本文概览
Future vs CompletableFuture
Future简介
在并发编程中,我们一般会使用Runnable编写任务的内容然后提交给线程池交由线程池调度线程执行。这种情况我们通常是针对不关心任务执行的结果,但如果关心任务执行的结果,并且根据执行结果执行后续的动作,这个时候就需要配合使用Callable+Future来实现了,其中Callable关注异步任务的执行,而Future则关注异步任务的执行结果,它提供了方法来检查任务是否完成,并在完成后获取结果。我们可以看下下面的代码:
java
复制代码package com.markus.concurrent.future;
import com.markus.concurrent.completable_future.utils.CommonUtils;
import java.util.concurrent.*;
/**
* @author: markus
* @date: 2023/9/11 11:10 PM
* @Description:
* @Blog: https://markuszhang.com
* It's my honor to share what I've learned with you!
*/
public class FutureHistory {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(new Runnable() {
@Override
public void run() {
System.out.println("Hello Runnable");
}
});
Future<String> callableFuture = pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "Hello Callable";
}
});
CommonUtils.sleep(1, TimeUnit.SECONDS);
// 一直阻塞等待
CommonUtils.printLog(callableFuture.get());
pool.shutdown();
}
}
Future的局限性
Future的出现解决了对异步任务结果的管理,但也存在一些局限性,具体如下:
-
在没有阻塞的情况下,无法对Future的结果执行进一步的操作。Future不会告知我们它什么时候完成,我们如果想要等待完成,则必须通过get()方法阻塞等待任务完成,Future不提供回调函数。
-
无法解决任务相互依赖的问题。filterWordFuture和newsFuture的结果不能自动发送给finalNewsFuture,需要在finalNewsFuture中手动获取,所以使用Future不能轻而易举地创建异步工作流。示例在下面。
-
不能将多个Future合并,比如你现在有两个异步任务A、B,如果要求A、B都执行完再去执行后续的逻辑,这个动作在Future中很难独立完成。
-
不能进行异常处理,Future.get调用时需要调用者手动去进行异常处理(显式抛出或捕获异常)。
java
复制代码package com.markus.concurrent.future;
import com.markus.concurrent.completable_future.utils.CommonUtils;
import java.util.concurrent.*;
/**
* @author: markus
* @date: 2023/9/11 11:23 PM
* @Description:
* @Blog: https://markuszhang.com
* It's my honor to share what I've learned with you!
*/
public class FutureLimit {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<String> newsFuture = pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return CommonUtils.readFile("news.txt");
}
});
Future<String> filterWordFuture = pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return CommonUtils.readFile("filter_word.txt");
}
});
Future<String> finalNews = pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
String news = newsFuture.get();
String filterWord = filterWordFuture.get();
// 将新闻中的敏感词过滤掉
String[] filterWords = filterWord.split(",");
for (String filter : filterWords) {
if (news.contains(filter)) {
news = news.replaceAll(filter, "**");
}
}
return news;
}
});
System.out.println(finalNews.get());
pool.shutdown();
}
}
CompletableFuture的优势
我们从类UML图中可以看到,CompletableFuture实现了Future和CompletionStage接口,它提供Future所能提供的功能,并相对于Future具有以下优势:
-
为快速创建、链接依赖和组合多个Future提供了大量的便利方法。
-
提供了适用于各种开发场景的回调函数,它还提供了非常全面的异常处理支持。
-
无缝衔接和亲和Lambda表达式和Stream API
-
真正意义上的异步编程,把异步编程和函数式编程、响应式编程多种高阶编程思维集于一身,设计上更优雅。
创建异步任务
CompletableFuture在异步任务创建上提供了如下方法:
java复制代码public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor);
public static CompletableFuture<Void> runAsync(Runnable runnable);
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor);
runAsync
如果要异步任务运行某些耗时的后台任务,并且不想从任务中返回任何内容,则可以使用CompletableFuture#runAsync()方法,它接受一个Runnable接口的实现类对象,方法返回CompletableFuture对象
java
复制代码package com.markus.concurrent.completable_future._01_completable_create;
import com.markus.concurrent.completable_future.utils.CommonUtils;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static com.markus.concurrent.completable_future.utils.CommonUtils.printLog;
import static com.markus.concurrent.completable_future.utils.CommonUtils.sleep;
/**
* @Author: zhangchenglong06
* @Date: 2023/9/4
* @Description:
*/
public class RunApiDemo {
public static void main(String[] args) {
System.out.println("main start");
/* lambda 写法 */
CompletableFuture<Void> futureLambda = CompletableFuture.runAsync(() -> {
String news = CommonUtils.readFile("news.txt");
printLog(news);
});
/*匿名内部类写法*/
CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
String news = CommonUtils.readFile("news.txt");
printLog(news);
}
});
printLog("main not blocked");
sleep(1, TimeUnit.SECONDS);
printLog("main end");
}
}