CompletableFuture之灭霸的故事

930 阅读6分钟

警告!!警告!!本文会剧透复联四!!还未观看过影片的同学慎重。

最近复联四上映,心疼灭霸。“归隐山林老农,竟招众人砍头”。

今天来说说CompletableFuture之灭霸的故事。

CompletableFuture,它是Java1.8提供的用来支持异步编程的工具类。在Java1.5里就提供了Future接口

我们知道Future是强大的但是在多任务有聚合关系的情况下用起来就有点麻烦,而CompletableFuture 就是用来解决任务之间的聚合关系的。对于灭霸来说他的得聚集六颗无限宝石,加上一个聚集宝石力量的手套,才能打响指!所以最终打响指这个任务依赖于聚集六颗宝石的任务和有手套。

CompletableFuture之灭霸的故事

话不多说先上代码,复联四的故事是这样的(因演示CompletableFuture需要,没有严格按照剧情)

        CompletableFuture<String> infinityStones = CompletableFuture.supplyAsync(() -> "六颗无限宝石");
        CompletableFuture<Void> mittens = CompletableFuture.runAsync(() -> {
            System.out.println("用于集合六颗无限宝石力量来打响指的手套");
        });
        CompletableFuture<String> thanosSnap = mittens.thenCombine(infinityStones, (m, stons) -> {
            System.out.println("获取" + stons);
            System.out.println("把宝石放到手套上");
            System.out.println("灭霸:我就是天命!(打响指)");
            int a = 1 / 0;       //钢铁侠挺身而出,替换了手套;
            return "呵呵寂寞,一群渣渣";
        }).exceptionally(e ->{
            System.out.println("钢铁侠抢夺了手套,举起手臂,轻轻打响指");
            return "钢铁侠:i am iron man";
        });
        System.out.println(thanosSnap.join());
        System.out.println("灭霸看着满天成灰的手下..心中流下了痛苦的泪水");
    }
     
     ##输出的故事情节如下
     用于集合六颗无限宝石力量来打响指的手套
     获取六颗无限宝石
     把宝石放到手套上
     灭霸:我就是天命!(打响指)
     钢铁侠抢夺了手套,举起手臂,轻轻打响指
     钢铁侠:i am iron man
     灭霸看着满天成灰的手下..心中流下了痛苦的泪水

可怜的灭霸就这样离开了我们,还有我们的钢铁侠帅的一批。I love you three thousand times.

CompletableFuture

咱们还是先回到CompletableFuture上,解释一下上面的方法。CompletableFuture主要是通过下面四个静态方法来创建的。

public static CompletableFuture<Void> runAsync(Runnable runnable) //使用默认线程池(ForkJoinPool)
public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) //使用传入的线程池
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) //使用默认线程池(ForkJoinPool)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) //使用传入的线程池

runAsyncsupplyAsync的差别在于runAsync方法不支持返回值而supplyAsync支持。

CompletionStage

这里还需要知道一个东西CompletionStage,它可以认为你的异步计算中的一个阶段,通过它可以很清晰的描述你的任务流的各任务之间的时序关系。如串行关系,and关系,or关系。CompletableFuture实现了CompletionStage

CompletionStage 接口中的串行方法

以下为CompletionStage接口中串行的方法,都是任务之间有依赖关系,必须一个任务执行完另一个任务才能执行。有Async的话就是不在当前线程内执行。异步再起一个线程执行。

thenApply 能接收参数也支持返回值,也就是接收上一阶段的输出作为本阶段的输入

thenAccept 支持接收参数但是没有返回值。

thenRun 不接受参数也不支持返回值,名副其实,就是run。

thenCompose 允许对两个 CompletionStage 进行流水线操作。

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)

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);

public CompletionStage<Void> thenRun(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action);
public CompletionStage<Void> thenRunAsync(Runnable action,Executor executor);

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) ;

CompletionStage 接口中and关系的方法

以下为CompletionStage接口中and关系的方法,强调的不是顺序而是两个任务都完成了就行,没先后的要求。我们上面代码用到的就是and关系。参数类型删掉了,就留个方法名有点印象就行了,具体还是得自己用的时候看。几个方法的差别就是参数的不同。

public <U,V> CompletionStage<V> thenCombine(other,fn);
public <U,V> CompletionStage<V> thenCombineAsync(other,fn);
public <U,V> CompletionStage<V> thenCombineAsync(other,fn,executor);

public <U> CompletionStage<Void> thenAcceptBoth(other,action);
public <U> CompletionStage<Void> thenAcceptBothAsync(other,action);
public <U> CompletionStage<Void> thenAcceptBothAsync(other,action, executor);

public CompletionStage<Void> runAfterBoth(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action);
public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other,Runnable action,Executor executor);

CompletionStage 接口中or关系的方法

or的关系就是两个任务,里面只要有一个完成就执行下一阶段的。如果是有返回值的话,那就是谁先返回用谁的结果执行下一个阶段的任务。

public <U> CompletionStage<U> applyToEither(other fn);
public <U> CompletionStage<U> applyToEitherAsync(other,fn);
public <U> CompletionStage<U> applyToEitherAsync(other, fn,executor);

public CompletionStage<Void> acceptEither(other,action);
public CompletionStage<Void> acceptEitherAsync(other,action);
public CompletionStage<Void> acceptEitherAsync(other,action,executor);

public CompletionStage<Void> runAfterEither(other,action);
public CompletionStage<Void> runAfterEitherAsync(other,action);
public CompletionStage<Void> runAfterEitherAsync(other,action,executor);

CompletionStage 异常处理

在上述的参数方法内是不能抛出可检查异常,但是运行有时候还是会异常。CompletionStage 就提供了以下几种处理异常的方法。 whenComplete和handle就类似try catch中的finally(我姓方平行四边形的方),反正会执行到这个方法,就可以用它来处理异常,两个的差别就是whenComplete不支持返回结果,handle支持。

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 <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);

public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)

总结

如果是任务之间有聚合关系就可以用CompletableFuture来解决!Java帮你写好的工具类不用白不用!


如有错误欢迎指正! 个人公众号:yes的练级攻略