Over a million developers have joined DZone.

Converting ListenableFutures to CompletableFutures and back

· DevOps Zone

Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

Java 8 introduced CompletableFutures. They build on standard Futures and add completion callbacks, chaining and other useful stuff. But the world did not wait for Java 8 and lot of libraries added different variants of ListenableFutures which serve the same purpose. Some library authors are reluctant to add support for CompletableFutures even today. It makes sense, Java 8 is quite new and it's not easy to add support for CompletableFutures and be compatible with Java 7 at the same time.

Luckily it's easy to convert to CompletableFutures and back. Let's take Spring 4 ListenableFutures as an example. How to convert it to CompletableFuture?

static <T> CompletableFuture<T> buildCompletableFuture(
		final ListenableFuture<T> listenableFuture
  ) {
  //create an instance of CompletableFuture
  CompletableFuture<T> completable = new CompletableFuture<T>() {
     @Override
     public boolean cancel(boolean mayInterruptIfRunning) {
        // propagate cancel to the listenable future
        boolean result = listenableFuture.cancel(mayInterruptIfRunning);
        super.cancel(mayInterruptIfRunning);
        return result;
     }
  };

  // add callback
  listenableFuture.addCallback(new ListenableFutureCallback<T>() {
      @Override
      public void onSuccess(T result) {
        completable.complete(result);
      }

      @Override
     public void onFailure(Throwable t) {
        completable.completeExceptionally(t);
     }
  });
  return completable;
}

We just create a CompletableFuture instance and add a callback to the ListenableFuture. In the callback method we just notify the CompletableFuture that the underlying task has finished. We can even propagate call to cancel method if we want to. That's all you need to convert to CompletableFuture.

What about the opposite direction? The approach is a bit different, but it's more or less straightforward as well

class ListenableCompletableFutureWrapper<T> implements ListenableFuture<T> {
    private final ListenableFutureCallbackRegistry<T> 
        callbackRegistry = new ListenableFutureCallbackRegistry<>();

    private final Future<T> wrappedFuture;

    ListenableCompletableFutureWrapper(
        CompletableFuture<T> wrappedFuture
    ) {
        this.wrappedFuture = wrappedFuture;
        wrappedFuture.whenComplete((result, ex) -> {
            if (ex != null) {
                if (ex instanceof CompletionException 
                    && ex.getCause() != null
                ) {
                    callbackRegistry.failure(ex.getCause());
                } else {
                    callbackRegistry.failure(ex);
                }
            } else {
                callbackRegistry.success(result);
            }
        });
    }

    @Override
    public void addCallback(
        ListenableFutureCallback<? super T> callback
    ) {
        callbackRegistry.addCallback(callback);
    }


    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return wrappedFuture.cancel(mayInterruptIfRunning);
    }

    @Override
    public boolean isCancelled() {
        return wrappedFuture.isCancelled();
    }

    @Override
    public boolean isDone() {
        return wrappedFuture.isDone();
    }

    @Override
    public T get() throws InterruptedException, ExecutionException {
        return wrappedFuture.get();
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return wrappedFuture.get(timeout, unit);
    }
}

We just wrap the CompletableFuture and again register a callback. The only non-obvious part is the use of ListenableFutureCallbackRegistry which keeps track of registered ListenableFutureCallbacks. We also have to do some exception processing, but that's all.

If you need to do something like this, I have good news. I have wrapped the code to a reusable library, so you do not have to copy and paste the code, you can just use it as described in the library documentation.

Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.

Topics:

Published at DZone with permission of Lukas Krecan. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}