Guava 如何才能将 future 投射到 listenablefuture 呢?

How can Guava just cast future to listenable future?

探索guava中的classes,了解guava带来的好处,虽然随着java8的推出,现在已经没那么重要了,但我还是想知道listenableFuture是如何引入的

AbstractListeningExecutorService中,有这样的代码片段:

  @Override
  public ListenableFuture<?> submit(Runnable task) {
    return (ListenableFuture<?>) super.submit(task);
  }

这里super表示AbstractListeningExecutorService的superclass,即ExecutorService,但是我们怎么能把一个superclass(Future)转成subclass( ListenableFuture) 这样的?

您会注意到 AbstractListeningExecutorService 的直接超类是 AbstractExecutorService,其中

Provides default implementations of ExecutorService execution methods. This class implements the submit, invokeAny and invokeAll methods using a RunnableFuture returned by newTaskFor, which defaults to the FutureTask class provided in this package.

默认值在 AbstractListeningExecutorService

中被覆盖

Abstract ListeningExecutorService implementation that creates ListenableFuture instances for each Runnable and Callable submitted to it

您还可以在链接到的源代码中看到

  /** @since 19.0 (present with return type {@code ListenableFutureTask} since 14.0) */
  @Override
  protected final <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    return TrustedListenableFutureTask.create(runnable, value);
  }

create return 是一个 TrustedListenableFutureTask 值,它是 ListenableFuture 的子类型。

重新声明 AbstractListeningExecutorService 中的那些方法,以便可以使它们的 return 类型更具体,即。 ListenableFuture.

由于 super.submit(..) 的 return 类型为 Future,因此 return 值必须转换为适当的子类型,即。 ListenableFuture 在这种情况下。由于所有调用 return 由 newTaskFor 创建的实例,因此已知它们将是类型 ListenableFuture 的实例。因此演员表是安全的。