Skip to content

Instantly share code, notes, and snippets.

@Spuffynism
Created August 12, 2017 23:07
Show Gist options
  • Save Spuffynism/7e8b91e52f295a025c361dca8d51bac2 to your computer and use it in GitHub Desktop.
Save Spuffynism/7e8b91e52f295a025c361dca8d51bac2 to your computer and use it in GitHub Desktop.
ListenableFuture to CompletableFuture Adapter
package com.springmvc.model;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.concurrent.CompletableFuture;
/**
* Converts a listenable future to a completable future, mapping the listenable futures' callbacks
* to the completable futures' equivalents.
*/
public class ListenableFutureAdapter {
public static <T> CompletableFuture<T> toCompletableFuture(
ListenableFuture<T> listenableFuture) {
CompletableFuture<T> completableFuture = new CompletableFuture<T>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
boolean cancelled = listenableFuture.cancel(mayInterruptIfRunning);
super.cancel(cancelled);
return cancelled;
}
};
listenableFuture.addCallback(completableFuture::complete,
completableFuture::completeExceptionally);
return completableFuture;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment