Search code examples
javaconcurrencyguavafuturetask

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


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.


Solution

  • 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.