Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
526 lines (399 loc) · 16.1 KB

File metadata and controls

526 lines (399 loc) · 16.1 KB
titleCompletableFuture入门
categoryJava
tag
Java并发

自己在项目中使用 CompletableFuture 比较多,看到很多开源框架中也大量使用到了 CompletableFuture

因此,专门写一篇文章来介绍这个 Java 8 才被引入的一个非常有用的用于异步编程的类。

简单介绍

CompletableFuture 同时实现了 FutureCompletionStage 接口。

publicclassCompletableFuture<T> implementsFuture<T>, CompletionStage<T> {
}

CompletableFuture 除了提供了更为好用和强大的 Future 特性之外,还提供了函数式编程的能力。

Future 接口有 5 个方法:

  • boolean cancel(boolean mayInterruptIfRunning) :尝试取消执行任务。
  • boolean isCancelled() :判断任务是否被取消。
  • boolean isDone() : 判断任务是否已经被执行完成。
  • get() :等待任务执行完成并获取运算结果。
  • get(long timeout, TimeUnit unit) :多了一个超时时间。

CompletionStage<T> 接口中的方法比较多,CompletableFuture 的函数式能力就是这个接口赋予的。从这个接口的方法参数你就可以发现其大量使用了 Java8 引入的函数式编程。

由于方法众多,所以这里不能一一讲解,下文中我会介绍大部分常见方法的使用。

常见操作

创建 CompletableFuture

常见的创建 CompletableFuture 对象的方法如下:

  1. 通过 new 关键字。
  2. 基于 CompletableFuture 自带的静态工厂方法:runAsync()supplyAsync()

new 关键字

通过 new 关键字创建 CompletableFuture 对象这种使用方式可以看作是将 CompletableFuture 当做 Future 来使用。

我在我的开源项目 guide-rpc-framework 中就是这种方式创建的 CompletableFuture 对象。

下面咱们来看一个简单的案例。

我们通过创建了一个结果值类型为 RpcResponse<Object>CompletableFuture,你可以把 resultFuture 看作是异步运算结果的载体。

CompletableFuture<RpcResponse<Object>> resultFuture = newCompletableFuture<>();

假设在未来的某个时刻,我们得到了最终的结果。这时,我们可以调用 complete() 方法为其传入结果,这表示 resultFuture 已经被完成了。

// complete() 方法只能调用一次,后续调用将被忽略。resultFuture.complete(rpcResponse);

你可以通过 isDone() 方法来检查是否已经完成。

publicbooleanisDone() {
returnresult != null;
}

获取异步计算的结果也非常简单,直接调用 get() 方法即可!

rpcResponse = completableFuture.get();

注意 : get() 方法并不会阻塞,因为我们已经知道异步运算的结果了。

如果你已经知道计算的结果的话,可以使用静态方法 completedFuture() 来创建 CompletableFuture

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!");
assertEquals("hello!", future.get());

completedFuture() 方法底层调用的是带参数的 new 方法,只不过,这个方法不对外暴露。

publicstatic <U> CompletableFuture<U> completedFuture(Uvalue) {
returnnewCompletableFuture<U>((value == null) ? NIL : value);
}

静态工厂方法

这两个方法可以帮助我们封装计算逻辑。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
// 使用自定义线程池(推荐)static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executorexecutor);
staticCompletableFuture<Void> runAsync(Runnablerunnable);
// 使用自定义线程池(推荐)staticCompletableFuture<Void> runAsync(Runnablerunnable, Executorexecutor);

runAsync() 方法接受的参数是 Runnable ,这是一个函数式接口,不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 runAsync() 方法。

@FunctionalInterfacepublicinterfaceRunnable {
publicabstractvoidrun();
}

supplyAsync() 方法接受的参数是 Supplier<U> ,这也是一个函数式接口,U 是返回结果值的类型。

@FunctionalInterfacepublicinterfaceSupplier<T> {
/** * Gets a result. * * @return a result */Tget();
}

当你需要异步操作且关心返回结果的时候,可以使用 supplyAsync() 方法。

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> System.out.println("hello!"));
future.get();// 输出 "hello!"CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "hello!");
assertEquals("hello!", future2.get());

处理异步结算的结果

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池public <U> CompletableFuture<U> thenApply(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(null, fn);
}
//使用默认的 ForkJoinPool 线程池(不推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn) {
returnuniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)public <U> CompletableFuture<U> thenApplyAsync(
Function<? superT,? extendsU> fn, Executorexecutor) {
returnuniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

thenAccept() 方法的参数是 Consumer<? super T>

publicCompletableFuture<Void> thenAccept(Consumer<? superT> action) {
returnuniAcceptStage(null, action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action) {
returnuniAcceptStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenAcceptAsync(Consumer<? superT> action,
Executorexecutor) {
returnuniAcceptStage(screenExecutor(executor), action);
}

顾名思义,Consumer 属于消费型接口,它可以接收 1 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceConsumer<T> {
voidaccept(Tt);
defaultConsumer<T> andThen(Consumer<? superT> after) {
Objects.requireNonNull(after);
return (Tt) -> { accept(t); after.accept(t); };
}
}

thenRun() 的方法是的参数是 Runnable

publicCompletableFuture<Void> thenRun(Runnableaction) {
returnuniRunStage(null, action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction) {
returnuniRunStage(defaultExecutor(), action);
}
publicCompletableFuture<Void> thenRunAsync(Runnableaction,
Executorexecutor) {
returnuniRunStage(screenExecutor(executor), action);
}

thenAccept()thenRun() 使用示例如下:

CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenAccept(System.out::println);//hello!world!nice!CompletableFuture.completedFuture("hello!")
.thenApply(s -> s + "world!").thenApply(s -> s + "nice!").thenRun(() -> System.out.println("hello!"));//hello!

whenComplete() 的方法的参数是 BiConsumer<? super T, ? super Throwable>

publicCompletableFuture<T> whenComplete(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(null, action);
}
publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action) {
returnuniWhenCompleteStage(defaultExecutor(), action);
}
// 使用自定义线程池(推荐)publicCompletableFuture<T> whenCompleteAsync(
BiConsumer<? superT, ? superThrowable> action, Executorexecutor) {
returnuniWhenCompleteStage(screenExecutor(executor), action);
}

相对于 ConsumerBiConsumer 可以接收 2 个输入对象然后进行“消费”。

@FunctionalInterfacepublicinterfaceBiConsumer<T, U> {
voidaccept(Tt, Uu);
defaultBiConsumer<T, U> andThen(BiConsumer<? superT, ? superU> after) {
Objects.requireNonNull(after);
return (l, r) -> {
accept(l, r);
after.accept(l, r);
};
}
}

whenComplete() 使用示例如下:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello!")
.whenComplete((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常System.out.println(res);
// 这里没有抛出异常所有为 nullassertNull(ex);
});
assertEquals("hello!", future.get());

异常处理

你可以通过 handle() 方法来处理任务执行过程中可能出现的抛出异常的情况。

public <U> CompletableFuture<U> handle(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(null, fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn) {
returnuniHandleStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> handleAsync(
BiFunction<? superT, Throwable, ? extendsU> fn, Executorexecutor) {
returnuniHandleStage(screenExecutor(executor), fn);
}

示例代码如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).handle((res, ex) -> {
// res 代表返回的结果// ex 的类型为 Throwable ,代表抛出的异常returnres != null ? res : "world!";
});
assertEquals("world!", future.get());

你还可以通过 exceptionally() 方法来处理异常情况。

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> {
if (true) {
thrownewRuntimeException("Computation error!");
}
return"hello!";
}).exceptionally(ex -> {
System.out.println(ex.toString());// CompletionExceptionreturn"world!";
});
assertEquals("world!", future.get());

如果你想让 CompletableFuture 的结果就是异常的话,可以使用 completeExceptionally() 方法为其赋值。

CompletableFuture<String> completableFuture = newCompletableFuture<>();
// ...completableFuture.completeExceptionally(
newRuntimeException("Calculation failed!"));
// ...completableFuture.get(); // ExecutionException

组合 CompletableFuture

你可以使用 thenCompose() 按顺序链接两个 CompletableFuture 对象。

public <U> CompletableFuture<U> thenCompose(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(null, fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn) {
returnuniComposeStage(defaultExecutor(), fn);
}
public <U> CompletableFuture<U> thenComposeAsync(
Function<? superT, ? extendsCompletionStage<U>> fn,
Executorexecutor) {
returnuniComposeStage(screenExecutor(executor), fn);
}

thenCompose() 方法会使用示例如下:

CompletableFuture<String> future
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "world!"));
assertEquals("hello!world!", future.get());

在实际开发中,这个方法还是非常有用的。比如说,我们先要获取用户信息然后再用用户信息去做其他事情。

thenCompose() 方法类似的还有 thenCombine() 方法, thenCombine() 同样可以组合两个 CompletableFuture 对象。

CompletableFuture<String> completableFuture
= CompletableFuture.supplyAsync(() -> "hello!")
.thenCombine(CompletableFuture.supplyAsync(
() -> "world!"), (s1, s2) -> s1 + s2)
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + "nice!"));
assertEquals("hello!world!nice!", completableFuture.get());

thenCompose()thenCombine() 有什么区别呢?

  • thenCompose() 可以两个 CompletableFuture 对象,并将前一个任务的返回结果作为下一个任务的参数,它们之间存在着先后顺序。
  • thenCombine() 会在两个任务都执行完成后,把两个任务的结果合并。两个任务是并行执行的,它们之间并没有先后依赖顺序。

并行运行多个 CompletableFuture

你可以通过 CompletableFutureallOf()这个静态方法来并行运行多个 CompletableFuture

实际项目中,我们经常需要并行运行多个互不相关的任务,这些任务之间没有依赖关系,可以互相独立地运行。

比说我们要读取处理 6 个文件,这 6 个任务都是没有执行顺序依赖的任务,但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 CompletableFuture 来处理。

示例代码如下:

CompletableFuture<Void> task1 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> task6 =
CompletableFuture.supplyAsync(()->{
//自定义业务操作
});
......
CompletableFuture<Void> headerFuture=CompletableFuture.allOf(task1,.....,task6);
try {
headerFuture.join();
} catch (Exceptionex) {
......
}
System.out.println("all done. ");

经常和 allOf() 方法拿来对比的是 anyOf() 方法。

allOf() 方法会等到所有的 CompletableFuture 都运行完成之后再返回

Randomrand = newRandom();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future1 done...");
}
return"abc";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000 + rand.nextInt(1000));
} catch (InterruptedExceptione) {
e.printStackTrace();
} finally {
System.out.println("future2 done...");
}
return"efg";
});

调用 join() 可以让程序等future1future2 都运行完了之后再继续执行。

CompletableFuture<Void> completableFuture = CompletableFuture.allOf(future1, future2);
completableFuture.join();
assertTrue(completableFuture.isDone());
System.out.println("all futures done...");

输出:

future1done...
future2done...
allfuturesdone...

anyOf() 方法不会等待所有的 CompletableFuture 都运行完成之后再返回,只要有一个执行完成即可!

CompletableFuture<Object> f = CompletableFuture.anyOf(future1, future2);
System.out.println(f.get());

输出结果可能是:

future2done...
efg

也可能是:

future1 done...
abc

后记

这篇文章只是简单介绍了 CompletableFuture 比较常用的一些 API 。

如果想要深入学习的话,可以多找一些书籍和博客看。

另外,建议G友们可以看看京东的 asyncTool 这个并发框架,里面大量使用到了 CompletableFuture