Converting google/guava ListenableFuture to Java 8 CompletableFuture

Java was a bit late in bringing Javascript's promise-like functionality. Future was there but wasn't as cool.

So people at google made ListenableFuture.

Now that java has CompletableFuture, it is common to run into problems like converting a ListenableFuture to a CompletableFuture. This can be because part of your older code uses ListenableFuture and now you have to compose your new logics utilising the newer and Java native technique.

Following is one possible way to do it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class FutureConverter {
    public static CompletableFuture toCompletableFuture(ListenableFuture listenableFuture) {
        final CompletableFuture completableFuture = new CompletableFuture();
        Futures.addCallback(listenableFuture, new FutureCallback() {
            public void onFailure(Throwable throwable) {
                completableFuture.completeExceptionally(throwable);
            }
            public void onSuccess(T t) {
                completableFuture.complete(t);
            }
        });
        return completableFuture;
    }
}

The toCompletableFuture method just attaches a callback to listenableFuture which returns a completableFuture wrapping the exception or the result of the ListenableFuture.

This is naive implementation of Adapter Design Pattern but the simplicity gets the job done.

Comments

Popular posts from this blog

SelfAwarePotato

A Generic method to convert ResultSetFuture (of Datastax Java driver for Cassandra) to a list of table-row-model(POJO) for any table query