分享

那些年我们追过的异步骚操作:ListenableFuture、CompletableFuture、RxJava(Observable)

 gideshi 2020-02-04

那些年我们追过的异步骚操作:ListenableFuture、CompletableFuture、RxJava(Observable)

原创 布道 最后发布于2019-03-13 22:07:26 阅读数 746 收藏
分类专栏: Java
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

Futures在Java 5(2004)中引入。它们是承诺在操作完成后保留操作结果的对象。调用者可以使用future对象来检查操作isDone(),或者等待它完成使用get()。Future模式一个最大的问题是何时调用问题(过早地阻塞Future.get(),这消除了异步执行的好处)。guava的 ListenableFuture、java8的 CompletableFuture、RxJava的 Observable 都给出了相应的解决方案,该如何选择这些,本文将就此展开探讨。

1. ListenableFuture

guava在很早的时候(估计Java 5)已经开源,它的增强主要是通过 MoreExecutor 和 Futures 两个类,如果你要研究源码也可以从他们下手。

  • ListenableFuture 继承了Future (jdk),额外新增了一个方法(任务结束后的回调方法),void addListener(Runnable listener, Executor executor);  其中executor是回调方法的执行器(通常是线程池)。需要注意的是不加Executor的情况,只适用于轻型的回调方法,如果回调方法很耗时占资源,会造成线程阻塞, 因为DirectExecutor有可能在主线程中执行回调
  • ListenableFutureTask 继承了FutureTask (jdk)并实现了ListenableFuture
  • ListeningExecutorService 继承 ExecutorService (jdk)接口,重写了submit方法,修改返回值类型为ListenableFuture

它提供的功能也特别多:

  • 监听任务执行结果并执行回调方法,Futures.addCallback
  • 提供方便的任务接口转换,Futures.transform()Futures.transformAsync()
  • 多线程并发执行取结果集合,Futures.allAsList()

注:Futures.transform()和Futures.addCallback()都是对addListener做了封装,进行回调的设置,但是transform更适合用在链式处理的中间过程,addCallback更适合用在处理最终的结果上。

  1. //线程池
  2. ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 5, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new CustomizableThreadFactory("demo"), new ThreadPoolExecutor.DiscardPolicy());
  3. ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(poolExecutor);
  4. //获得一个随着jvm关闭而关闭的线程池,通过Runtime.getRuntime().addShutdownHook(hook)实现,修改ThreadFactory为创建守护线程,默认jvm关闭时最多等待120秒关闭线程池,重载方法可以设置时间
  5. ExecutorService newPoolExecutor = MoreExecutors.getExitingExecutorService(poolExecutor);
  6. //只增加关闭线程池的钩子,不改变ThreadFactory
  7. MoreExecutors.addDelayedShutdownHook(poolExecutor, 120, TimeUnit.SECONDS);
  8. //提交任务
  9. ListenableFuture<String> listenableFuture = listeningExecutor.submit(new Callable<String>() {
  10. @Override
  11. public String call() throws Exception {
  12. return "";
  13. }
  14. });
  15. //注册回调
  16. Futures.addCallback(listenableFuture, new FutureCallback<String>() {
  17. @Override
  18. public void onSuccess(String result) {
  19. }
  20. @Override
  21. public void onFailure(Throwable t) {
  22. }
  23. });
  24. /**
  25. * 链式语法
  26. **/
  27. ListenableFutureTask<String> task1 = ListenableFutureTask.create(new Callable<String>() {
  28. @Override
  29. public String call() throws Exception {
  30. return "";
  31. }
  32. });
  33. new Thread(task1).start();
  34. task1.addListener(new Runnable() {
  35. @Override
  36. public void run() {
  37. ListenableFutureTask<String> task2 = ListenableFutureTask.create(new Callable<String>() {
  38. @Override
  39. public String call() throws Exception {
  40. return "";
  41. }
  42. });
  43. task2.addListener(new Runnable() {
  44. @Override
  45. public void run() {
  46. ...
  47. }
  48. }, MoreExecutors.directExecutor());
  49. new Thread(task2).start();
  50. }
  51. }, MoreExecutors.directExecutor());
  52. ListenableFuture<String> task2 = Futures.transform(task1, new Function<String, String>() {
  53. @Override
  54. public String apply(String input) {
  55. return "";
  56. }
  57. });
  58. ListenableFuture<String> task3 = Futures.transform(task2, new Function<String, String>() {
  59. @Override
  60. public String apply(String input) {
  61. return "";
  62. }
  63. });
  64. //处理最终的异步任务
  65. Futures.addCallback(task3, new FutureCallback<String>() {
  66. @Override
  67. public void onSuccess(String result) {
  68. }
  69. @Override
  70. public void onFailure(Throwable t) {
  71. }
  72. });

2. CompletableFuture

JDK8中开始引入的CompletableFuture,实际上是由Google的ListenableFuture 启发的常规期货的演变,所以在一定程度上他们非常类似,但它提供了更强大的 Future 的扩展功能。比如:ListenableFuture 的addCallback监听回调,相当于thenRun或者whenComplete操作原语。

  • CompletionStage,代表异步计算过程中的某一个阶段,一个阶段完成以后可能会触发另外一个阶段,一个阶段的计算执行可以是一个Function,Consumer或者Runnable
  • CompletableFuture,它实现了Future CompletionStage,它提供了函数式编程的能力,可以通过回调的方式处理计算结果,也提供了转换和组合的方法。原理:内部通过阻塞队列+FutureTask,实现了任务先完成可优先获取到,即结果按照完成先后顺序排序。

回调函数的线程

提供了非异步的完成操作,没有显式入参Executor的所有async方法都使用 ForkJoinPool.commonPool()为了简化监视、调试和跟踪,所有生成的异步任务都是标记接口 AsynchronousCompletionTask的实例。注意:这些线程都是Daemon线程,主线程结束Daemon线程不结束,只有JVM关闭时,生命周期终止

  1. public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {
  2. /**
  3. * 四种创建异步任务(*Async)
  4. * runAsync则用于没有返回值的异步任务
  5. * supplyAsync用于有返回值的异步任务
  6. **/
  7. public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
  8. public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)
  9. public static CompletableFuture<Void> runAsync(Runnable runnable)
  10. public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
  11. /**
  12. * 本stage出现了异常,会进入,可以对异常处理再返回新的CompletionStage
  13. **/
  14. public CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn)
  15. /**
  16. * 本stage正常完成后或出现了异常,来执行无需返回值的Action
  17. * 不以Async结尾的方法由原来的线程计算,以Async结尾的方法由默认的线程池ForkJoinPool.commonPool()
  18. **/
  19. public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
  20. public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
  21. public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)
  22. public CompletableFuture<T> exceptionally(Function<Throwable,? extends T> fn)
  23. /**
  24. * 转换
  25. * 本stage完成后(转换并不是马上执行的,也不会阻塞,而是在前一个stage完成后继续执行),用其结果构建一个新的stage并返回
  26. **/
  27. public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)
  28. public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
  29. public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)
  30. /**
  31. * 转换和异常处理的两个功能
  32. * 相当于thenApply和exceptionally加强版,可操作空间大
  33. **/
  34. public <U> CompletableFuture<U> handle(BiFunction<? super T,Throwable,? extends U> fn)
  35. public <U> CompletableFuture<U> handleAsync(BiFunction<? super T,Throwable,? extends U> fn)
  36. public <U> CompletableFuture<U> handleAsync(BiFunction<? super T,Throwable,? extends U> fn, Executor executor)
  37. /**
  38. * 纯消费(执行Void Action)
  39. * 本stage完成后,来执行无需返回值的 Consumer
  40. **/
  41. public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
  42. public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)
  43. public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor)
  44. //与thenAccept不同,下面三个不使用计算的结果
  45. public CompletableFuture<Void> thenRun(Runnable action)
  46. public CompletableFuture<Void> thenRunAsync(Runnable action)
  47. public CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor)
  48. /**
  49. * 纯消费2
  50. * 当两个CompletionStage都正常完成计算的时候,会执行提供的action/Runnable
  51. **/
  52. public <U> CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
  53. public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action)
  54. public <U> CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T,? super U> action, Executor executor)
  55. public CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
  56. public CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
  57. /**
  58. * 组合
  59. * 本stage正常完成后,用其结果构造一个新的stage,和thenApply类似,只不过这个需要自己构造stage,thenApply会自动构造,它对于构建异步的pipeline非常有用
  60. **/
  61. public <U> CompletableFuture<U> thenCompose(Function<? super T,? extends CompletionStage<U>> fn)
  62. public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn)
  63. public <U> CompletableFuture<U> thenComposeAsync(Function<? super T,? extends CompletionStage<U>> fn, Executor executor)
  64. /**
  65. * 组合2
  66. * 本stage和给定的stage都正常完成后,执行一个BiFunction
  67. * 两个stage是并行执行的,它们之间并没有先后依赖顺序,与thenAcceptBoth区别在于有返回值
  68. **/
  69. public <U,V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
  70. public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)
  71. public <U,V> CompletableFuture<V> thenCombineAsync(CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor)
  72. /**
  73. * Either
  74. * 当任意一个stage完成的时候,action这个消费者就会被执行
  75. * applyToEither方法是当任意一个stage完成的时候,fn会被执行,它的返回值会当作新的CompletableFuture<U>的计算结果
  76. **/
  77. public CompletableFuture<Void> acceptEither(CompletionStage<? extends T> other, Consumer<? super T> action)
  78. public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action)
  79. public CompletableFuture<Void> acceptEitherAsync(CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor)
  80. public <U> CompletableFuture<U> applyToEither(CompletionStage<? extends T> other, Function<? super T,U> fn)
  81. public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn)
  82. public <U> CompletableFuture<U> applyToEitherAsync(CompletionStage<? extends T> other, Function<? super T,U> fn, Executor executor)
  83. /**
  84. * allOf 和 anyOf
  85. * allOf方法是当所有的CompletableFuture都执行完后执行计算
  86. * anyOf方法是当任意一个CompletableFuture执行完后就会执行计算,计算的结果相同
  87. **/
  88. public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
  89. public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs)
  90. }
  1. public class CompletableFuture_test {
  2. private CompletableFuture<Integer> compFuture = CompletableFuture.supplyAsync(() -> {
  3. System.out.println("compFuture");
  4. return 100;
  5. });
  6. private long getTimeStamp() {
  7. long timeMillis = System.currentTimeMillis();
  8. if (timeMillis % 2 == 0) throw new RuntimeException("custom uncheck exception");
  9. return timeMillis;
  10. }
  11. //正常or异常
  12. @Test
  13. public void go_whenComplete() throws ExecutionException, InterruptedException {
  14. CompletableFuture<Long> compFuture2 = CompletableFuture.supplyAsync(this::getTimeStamp);
  15. Future<Long> future = compFuture2.whenComplete((v, e) -> {
  16. System.out.println(v);//exception时 null
  17. System.out.println("exception:" + e);
  18. });
  19. System.out.println("result:" + future.get());
  20. }
  21. //转换
  22. @Test
  23. public void go_thenApplyAsync() throws ExecutionException, InterruptedException {
  24. CompletableFuture<String> compFuture2 = compFuture.thenApplyAsync(x -> x * 10).thenApply(x -> x.toString());
  25. System.out.println(compFuture2.get());
  26. }
  27. //纯消费
  28. @Test
  29. public void go_thenAccept_thenAcceptBoth() throws ExecutionException, InterruptedException {
  30. CompletableFuture<Void> f = compFuture.thenAccept(System.out::println);
  31. System.out.println(f.get());//返回null
  32. //两个CompletionStage都正常完成时执行
  33. CompletableFuture<Void> f2 = compFuture.thenAcceptBoth(CompletableFuture.completedFuture(10),
  34. (x, y) -> System.out.println(x * y));
  35. System.out.println(f2.get());
  36. }
  37. @Test
  38. public void go_thenRun() throws ExecutionException, InterruptedException {
  39. CompletableFuture<Void> f = compFuture.thenRun(() -> System.out.println("finished"));
  40. System.out.println(f.get());
  41. }
  42. //组合
  43. @Test
  44. public void go_thenCompose() throws ExecutionException, InterruptedException {
  45. //一个个排队
  46. CompletableFuture<String> f = compFuture.thenCompose(i -> {
  47. return CompletableFuture.supplyAsync(() -> {
  48. return (i * 10) + "";
  49. });
  50. });
  51. System.out.println(f.get());
  52. CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
  53. return "abc";
  54. });
  55. //并行
  56. CompletableFuture<String> f2 = compFuture.thenCombine(future2, (x, y) -> y + "-" + x);
  57. System.out.println(f2.get()); //abc-100
  58. }
  59. //当任意一个完成
  60. @Test
  61. public void go_applyToEither() throws ExecutionException, InterruptedException {
  62. CompletableFuture<Integer> compFuture2 = CompletableFuture.supplyAsync(() -> 2);
  63. CompletableFuture<String> f = compFuture.applyToEither(compFuture2, i -> i.toString());
  64. System.out.println(f.get());
  65. }
  66. @Test
  67. public void go_allOf_anyOf() throws ExecutionException, InterruptedException {
  68. CompletableFuture<Integer> compFuture2 = CompletableFuture.supplyAsync(() -> 2);
  69. CompletableFuture<Integer> compFuture3 = CompletableFuture.supplyAsync(() -> 4);
  70. //所有完成
  71. CompletableFuture<Object> f = CompletableFuture.anyOf(compFuture, compFuture2, compFuture3);
  72. //任何一个
  73. //CompletableFuture<Void> f = CompletableFuture.anyOf(compFuture,compFuture2,compFuture3);
  74. System.out.println(f.get());
  75. }
  76. // @Test
  77. // public void getProductById(String productId) throws InterruptedException, ExecutionException {
  78. // CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> getProductDetailInfo(productId));
  79. // CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> getProductSkuInfo(productId));
  80. // //等待三个数据源都返回后,再组装数据。这里会有一个线程阻塞
  81. // CompletableFuture.allOf(f1, f2).join();
  82. //
  83. // String detail = f1.get();
  84. // String sku = f2.get();
  85. // System.out.println(detail + "@" + sku);
  86. // }
  87. //汇总计算结果
  88. @Test
  89. public void go_sequence() throws ExecutionException, InterruptedException {
  90. CompletableFuture<Integer> compFuture2 = CompletableFuture.supplyAsync(() -> 2);
  91. CompletableFuture<Integer> compFuture3 = CompletableFuture.supplyAsync(() -> 4);
  92. List<CompletableFuture<Integer>> futures= Lists.newArrayList(compFuture,compFuture2,compFuture3);
  93. CompletableFuture<List<Integer>> f = sequence(futures);
  94. System.out.println(f.get());
  95. }
  96. //拓展:内部是通过allOf和lamda实现的
  97. public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) {
  98. CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
  99. return allDoneFuture.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.<T>toList()));
  100. }
  101. }

小结

Runnable类型的参数会忽略计算的结果,Consumer是纯消费计算结果,BiConsumer会组合另外一个CompletionStage纯消费,Function会对计算结果做转换,BiFunction会组合另外一个CompletionStage的计算结果做转换。

thenApply 与handle方法的区别?

handle方法会处理正常计算值和异常,因此它可以屏蔽异常,避免异常继续抛出。而thenApply 方法只是用来处理正常值,因此一旦有异常就会抛出。

3. RxJava

RxJava 用于reactive programming,它似乎与Java 8's streams相似,但是它更强大。Java 9 Reactive Streams 也有它的身影。

Futures 类似,RxJava可用于将一堆同步或异步操作串联起来以产生一个或多个有意义的结果。然而,与一次性使用的Futures不同,RxJava可以处理零个或多个项目的流,包括具有无限数量项目的永无止境的流。由于令人难以置信的丰富set of operators,它也更加灵活和流畅。

与Java 8的流不同,RxJava具有backpressure机制,允许它处理处理流的不同部分以不同的速率在不同的线程中运行的情况。

RxJava的缺点是,尽管有相当好的文档(之前也分享过),但由于涉及范式转换,它是一个具有挑战性的库。 Rx代码也可能是调试的噩梦,特别是如果涉及多个线程,更糟糕的是 - 如果需要背压。

4. 总结

如果你想要写出高逼格的代码,更友好的链式调用,更方便的维护代码,要解决谜之缩进确实是个挑战,而RxJava正是符合你的意愿。

参阅资料

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多