问题
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