Skip to content

Instantly share code, notes, and snippets.

@kofemann
Last active April 6, 2023 07:36
Show Gist options
  • Save kofemann/a721af324f8c35f6e9840f583ca40f05 to your computer and use it in GitHub Desktop.
Save kofemann/a721af324f8c35f6e9840f583ca40f05 to your computer and use it in GitHub Desktop.
Howto migrate from guava's Listenablefuture to java8 completableFuture

Guava -> Java 8 cheat sheet

This is a one way mapping. If you used to use Guava futures, you probably want to do the java 8 equivalent. This does not mean that the reverse mapping works.

Guava style Java 8 style
Listenablefuture.addListener(callback) future.whenComplete(callback)
Futures.addCallback(callback) future.whenComplete(callback)
Futures.transform(future, function) future.thenApply(function)
Futures.transform(future, asyncFunction) future.thenCompose(function)
Futures.dereference(future) future.thenCompose(stage -> stage)
Futures.immediateFuture(value) CompletableFuture.completedFuture(value)
Futures.immediateFailedFuture(throwable) new CompletableFuture().completeExceptionally(throwable)
Futures.withFallback(future, function) future.exceptionally(function)
SettableFuture.create() new CompletableFuture()
Futures.nonCancellationPropagating(future) future.thenApply(Function.identity()

Futures.withFallback(future, asyncFunction) can be mapped to

stage
  .thenApply(v -> CompletableFuture.completedFuture(v))
  .exceptionally(asyncFunction)
  .thenCompose(stage -> stage)

Subtle differences

Guava uses the terms Function and AsyncFunction where Async means that the function returns a new future. (This means that all methods that use a regular Function can be implemented with the method that takes an AsyncFunction and wraps the value in a Futures.immediateFuture(x).)

The equivalent of methods that take an AsyncFunction in Java 8 is thenCompose (but that is only implemented for successful futures, not exceptions).

If you want to transform an exception by returning a different future you have to use a workaround (see below).

There are Async variants of the methods for futures in Java 8 too, but that means something completely different: the function or callback you pass in will just be executed on a different thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment