异步利刃CompletableFuture

什么是CompletableFuture?

CompletableFuture 类实现了 Future 和 CompletionStage 接口并且新增了许多方法,它支持 lambda,通过回调利用非阻塞方法,提升了异步编程模型。简单来说可以帮我们实现任务编排。【文中所有代码已上传码云

CompletableFuture的创建

先来看一个创建例子,后续再展开说说这个类中的方法:

CompletableFuture<String> completableFuture = new CompletableFuture<>();
completableFuture.complete("Hello CompletableFuture");
System.out.println(completableFuture.get());

需要注意的是当我们对不完整的 CompleteableFuture调用 get 方法的话,会由于 Future 未完成,因此 get 调用会一直阻塞。

创建异步任务

CompletableFuture 提供了四个静态方法来创建异步任务。

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor);

public static CompletableFuture<Void> runAsync(Runnable runnable);
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor);

没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码;如果指定线程池,则使用指定的线程池运行。

    static Executor screenExecutor(Executor e) {
        if (!useCommonPool && e == ForkJoinPool.commonPool())
            return asyncPool;
        if (e == null) throw new NullPointerException();
        return e;
    }

二者的区别很明显,supplyAsync有返回值,runAsync方法无返回值。我们通过静态方法会立刻开启异步线程执行Supplier或者Runnable提交的任务。任务执行完成,就可以打印返回值,不再需要其它线程主动调用complete来表示任务执行完成。

获取任务执行结果

public T get();
public T get(long timeout, TimeUnit unit);
public T getNow(T valueIfAbsent);
public T join();

get()和get(long timeout, TimeUnit unit)是实现了Future接口的功能,两者主要区别就是get()会一直阻塞直到获取到结果,get(long timeout, TimeUnit unit)值可以指定超时时间,当到了指定的时间还未获取到任务,就会抛出TimeoutException异常。

getNow(T valueIfAbsent):就是获取任务的执行结果,但不会产生阻塞。如果任务还没执行完成,那么就会返回你传入的 valueIfAbsent 参数值,如果执行完成了,就会返回任务执行的结果。

join():跟get()的主要区别就是,get()会抛出检查时异常,join()不会。

任务完成后的处理

whenComplete

public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

whenComplete是等任务完成后继续执行whenComplete的action,这里也能看出执行action的是主线程

如果有异常,当主线程在获取任务结果时就会抛出异常。

而whenCompleteAsync是通过异步线程去执行action

exceptionally

任务执行过程中出现异常的时候,会回调exceptionally方法指定的回调,但是如果没有出现异常,是不会回调的。

thenApply

当线程B依赖于线程A的执行结果时,可以使用thenApply方法来把这两个线程串行化

public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)

将supplyAsync方法里的结果(Integer)作为thenApply方法里Function接口的apply方法的入参

如果有异常thenApply就不会执行

handle

public <U> CompletionStage<U> handle(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn);
public <U> CompletionStage<U> handleAsync(BiFunction<? super T, Throwable, ? extends U> fn,Executor executor);

不同于thenApply的是handle里的方法是在supplyAsync/runAsync执行后一定会执行。

thenAccept

public CompletionStage<Void> thenAccept(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action);
public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action,Executor executor);

不同于上述的方法,thenAccept纯消费无返回值。

组合任务

thenCompose

这个方法也是线程B需要用到线程A的结果,不同于thenApply的是:thenCompose()用来连接两个CompletableFuture,返回值是新的CompletableFuture;thenApply()转换的是泛型中的类型,是同一个CompletableFuture。

public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn)
public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn, Executor executor)

thenCombine

会把两个CompletableFuture的任务都执行完成后把结果一块交给thenCombine来处理,并生成新的CompletableFuture任务。

public <U,V> CompletionStage<V> thenCombine(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn);
public <U,V> CompletionStage<V> thenCombineAsync(CompletionStage<? extends U> other,BiFunction<? super T,? super U,? extends V> fn,Executor executor);

谁调用的thenCombine,则BiFunction的第一个参数就是它的结果。

其他方法

allOf

allOf方法的入参是多个CompletableFuture任务,返回类型是CompletableFuture<Void>,allOf方法是等所有的CompletableFuture都执行完后再执行计算,一般后面会跟链式的thenApply方法或者thenAccept方法对所有的异步任务进行汇总处理。

anyOf

anyOf方法入参也是多个CompletableFuture任务,返回类型是CompletableFuture<Object>,anyOf方法只要有一个CompletableFuture任务完后就执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java异步调用CompletableFuture是一种非常强大的工具,它可以帮助我们处理异步编程的复杂性。下面是一个简单的示例,展示了CompletableFuture的基本用法: ```java import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CompletableFutureExample { public static void main(String[] args) { // 创建一个线程池 ExecutorService executor = Executors.newFixedThreadPool(3); // 异步执行任务 CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello, World!"; }, executor); // 注册回调函数 future.thenAccept(result -> System.out.println("Result: " + result)); // 关闭线程池 executor.shutdown(); } } ``` 在上面的例子中,我们首先创建了一个线程池,然后使用`CompletableFuture.supplyAsync()`方法将任务异步执行。在这个示例中,任务会休眠1秒钟,然后返回一个字符串结果"Hello, World!"。 接下来,我们通过调用`thenAccept()`方法注册了一个回调函数,该函数会在任务完成后被调用,并且会打印出结果。 最后,我们关闭了线程池。 需要注意的是,CompletableFuture还提供了很多其他的方法,可以帮助我们实现更加复杂的异步编程逻辑,比如`thenApply()`、`thenCompose()`、`thenCombine()`等等。你可以根据具体的需求选择适合的方法来使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LoneWalker、

你的鼓励是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值