Created
August 12, 2017 23:07
-
-
Save Spuffynism/7e8b91e52f295a025c361dca8d51bac2 to your computer and use it in GitHub Desktop.
ListenableFuture to CompletableFuture Adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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