IT评测·应用市场-qidao123.com

标题: 深入理解 Future, CompletableFuture, ListenableFuture,回调机制 [打印本页]

作者: 刘俊凯    时间: 2025-1-23 00:13
标题: 深入理解 Future, CompletableFuture, ListenableFuture,回调机制
深入理解 Future, CompletableFuture, ListenableFuture,回调机制

本文禁止转载。
本文从设计思想、详细实现等角度分析了 Future、CompletableFuture、ListenableFuture等接口或类,提出了一些最佳实践,英华内容为示例代码。耐心看完,相信你一定会有所收获。文章首发公众号,欢迎关注。
理想的 Future

现实的 Future 接口

  1. V get() throws InterruptedException, ExecutionException;
  2. V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
复制代码
  1. boolean cancel(boolean mayInterruptIfRunning);
复制代码
在 JDK19 终于提供了以下一系列方法,其基本思想就是值类型,绕过 get 阻塞调用的弊端。当已知结果已经得出后,直接取值,无需进行受检异常处置处罚。美中不足:停止机制还是不视为异常的一部门,exceptionNow 在停止状态时,还是会停止当前线程。
  1. default V resultNow();
  2. default Throwable exceptionNow();
  3. default State state();
  4. enum State {
  5.       /**
  6.        * The task has not completed.
  7.        */
  8.       RUNNING,
  9.       /**
  10.        * The task completed with a result.
  11.        * @see Future#resultNow()
  12.        */
  13.       SUCCESS,
  14.       /**
  15.        * The task completed with an exception.
  16.        * @see Future#exceptionNow()
  17.        */
  18.       FAILED,
  19.       /**
  20.        * The task was cancelled.
  21.        * @see #cancel(boolean)
  22.        */
  23.       CANCELLED
  24. }
复制代码
总之,新增的默认方法利用必要先进行状态判定,然后调用获取结果方法。以下是代码示例:
  1. // 处理已运算结果
  2. results = futures.stream()
  3.            .filter(f -> f.state() == Future.State.SUCCESS)
  4.            .map(Future::resultNow)
  5.            .toList();
  6. // allOf 运算结果处理
  7. CompletableFuture.allOf(c1, c2, c3).join();
  8. foo(c1.resultNow(), c2.resultNow(), c3.resultNow());
复制代码
不过,默认方法对于第三方库来说可能会出现运行题目,必要确认第三方库支持再利用默认方法。
CompletableFuture 大幅改进

岁月史书:Future, ExecutorService, BlockingQueue, AQS 等在 JDK1.5 推出,随后 Google Guava 类库提供了 ListenableFuture 补全了 Future 的回调功能,CompletableFuture 鉴戒了 ListenableFuture 功能,联合函数式支持,在 JDK1.8 推出。
1. 链式调用
  1. public class CompletableFuture<T> implements Future<T>, CompletionStage<T>
复制代码
大部门链式调用方法界说在 CompletionStage 中:
[table][tr]CompletionStage 接口方法函数式接口Stream 相似方法[/tr][tr][td]<U> CompletionStage<U> thenApply(Function




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4