如何将Java Future<V>转换为番石榴ListenableFuture<V>



我需要找到一种从未来转换为可听图的方法。目前,我正在使用一项将来返回未来的服务,但我需要将听众连接到它。我无法更改服务界面,因为它不属于我。

有一种简单的方法可以做到吗?

我已经阅读了Guava文档,但我仍然找不到方法。

guava为此转换提供了JdkFutureAdapters类型。API状态

与供应普通的图书馆合作所必需的公用事业 未来实例。

例如

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

但是您应该小心地使用它:当您已经已经提交了任务时,很难模仿可听的未来,因此Guava采用了一个新线程并在那里阻止直到原始Future完成。

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

未来只是获得界面,而guava listableFuture是未来的接口,即在set或setException时由完整(setException)运行的注册运行的侦听器(由guava AbstractFuture实现)。

实现。
import com.google.common.util.concurrent.AbstractFuture;
import java.util.concurrent.Future;
public class ListenerFuture<V> extends AbstractFuture<V> {
    public ListenerFuture(Future<V> future){
        this.future= future;
    }
    // blocking in future get, then run listener in AbstractFuture set
    public void fireListener(){
        try {
            super.set(future.get());
        }catch (Exception e){
            throw new RuntimeException("guava set ListenableFuture", e);
        }
    }
    private Future<V> future;
}
ListenerFuture<V> response= new ListenerFuture(service.response());
response.addListener(Runnable, Executor);
// pass the ListenableFuture to whom need it
// do something else until who must have service response call the blocking
response.fileListner()

番石榴摘要空格有其局限性:

  1. 听众是列表,但通常只使用1个 - 过度杀伤。如果需要多个听众,请将其分配在听众内部或使用消息来考虑您的设计。
  2. setException set返回值作为异常,因此用户必须使用实例来区分异常,或者不使用get()
  3. 在将来的管道中,太多的层AddListener()使代码难以阅读。

我更喜欢ploteablefuture.supply()。thenapply()。

最新更新