how to convert java Future<V> to guava ListenableFuture<V>

最后都变了- 提交于 2019-12-08 16:00:37

问题


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.

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:


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

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

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.

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



来源:https://stackoverflow.com/questions/30159229/how-to-convert-java-futurev-to-guava-listenablefuturev

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!