Java – Use Case for Implementing a Callback if a Future is Returned

asynchronous-programmingconcurrencyjavamultithreading

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?

Best Answer

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.