5

If I have function which returns a future, is there any reason to also include a callback where the callback is simply called right before the future completes?

The only advantage I can think of would be to guarantee that some action be performed prior to any tasks pending on the future and also that the action be guaranteed to occur within the same thread of the future's callee.

Are there any use cases or practical applications for this?

1 Answer 1

4

The Guava Library has the concept of a ListenableFuture and a SettableFuture.

A ListenableFuture allows you to register callbacks to be executed once the computation is complete, or if the computation is already complete, immediately. This simple addition makes it possible to efficiently support many operations that the basic Future interface cannot support.

Because the Runnable interface does not provide direct access to the Future result, users who want such access may prefer Futures.addCallback. A FutureCallback<V> implements two methods:

  • onSuccess(V), the action to perform if the future succeeds, based on its result
  • onFailure(Throwable), the action to perform if the future fails, based on the failure

The most important reason to use ListenableFuture is that it becomes possible to have complex chains of asynchronous operations.

When several operations should begin as soon as another operation starts ("fan-out"), ListenableFuture just works: it triggers all of the requested callbacks. With slightly more work, we can "fan-in," or trigger a ListenableFuture to get computed as soon as several other futures have all finished: see the implementation of Futures.allAsList for an example.

In .NET, these concepts are implemented using Task, TaskCompletionSource and ContinueWith.

2
  • 1
    In Java 1.8 it is called CompletionStage.
    – Basilevs
    May 2, 2016 at 3:15
  • Google APIs for Android has a similar TaskCompletionSource class, which allows creation of Task-enabled APIs. ("Tasks" are asynchronous operations with callbacks.)
    – varun
    Apr 8, 2019 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.