如何将java Future 转换为guava ListenableFuture

时间:2021-11-20 20:49:20

I need to find a way to convert from Future to ListenableFuture. Currently i'm using a service which returns Future but i need to hook up a listener to it. I can't change the service interface as it doesn't belong to me.

我需要找到一种从Future转换为ListenableFuture的方法。目前我正在使用一个返回Future的服务,但我需要连接一个监听器。我无法更改服务界面,因为它不属于我。

Is there a simple way to do that ?

有一个简单的方法吗?

I have read guava docs but still i can't find a way to do it.

我已经阅读了番石榴文档,但我仍然找不到办法。

1 个解决方案

#1


Guava provides the JdkFutureAdapters types for this conversion. The API states

Guava为此转换提供了JdkFutureAdapters类型。 API声明

Utilities necessary for working with libraries that supply plain Future instances.

使用提供简单Future实例的库所必需的实用程序。

For example

Future<?> future = ...;
ListenableFuture<?> listenable = JdkFutureAdapters.listenInPoolThread(future);

But you should use it with care: it's hard to emulate listenable future when you already have submitted task, because there is no way to put a hook on completion there, so Guava takes a new thread and blocks there until original Future is completed.

但是你应该谨慎使用它:当你已经提交任务时很难模仿可听的未来,因为没有办法在那里完成钩子,所以Guava接受一个新的线程并阻塞那里直到原始的Future完成。

The Guava Wiki also contains some information on this specific case.

Guava Wiki还包含有关此特定案例的一些信息。

#1


Guava provides the JdkFutureAdapters types for this conversion. The API states

Guava为此转换提供了JdkFutureAdapters类型。 API声明

Utilities necessary for working with libraries that supply plain Future instances.

使用提供简单Future实例的库所必需的实用程序。

For example

Future<?> future = ...;
ListenableFuture<?> listenable = JdkFutureAdapters.listenInPoolThread(future);

But you should use it with care: it's hard to emulate listenable future when you already have submitted task, because there is no way to put a hook on completion there, so Guava takes a new thread and blocks there until original Future is completed.

但是你应该谨慎使用它:当你已经提交任务时很难模仿可听的未来,因为没有办法在那里完成钩子,所以Guava接受一个新的线程并阻塞那里直到原始的Future完成。

The Guava Wiki also contains some information on this specific case.

Guava Wiki还包含有关此特定案例的一些信息。