how to convert java Future to guava ListenableF

2019-06-16 16:05发布

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条回答
可以哭但决不认输i
2楼-- · 2019-06-16 16:45

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.

查看更多
登录 后发表回答