Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring mvc: the difference between DeferredResult and ListenableFuture?

Spring MVC lets controllers return DeferredResult and ListenableFuture (which is implemented by ListenableFutureTask) to do async response. What's the difference? When should I use each of them?

like image 695
piotrek Avatar asked Jun 17 '16 04:06

piotrek


2 Answers

They are conceptually similar to each other and can be used interchangeably as a controller's method result, thanks to ListenableFutureReturnValueHandler that adapts the second to the first one.

However, both DeferredResult class and ListenableFuture interface come from two different worlds:

  1. First from org.springframework.web.context.request.async package added in version 3.2.
  2. Second from org.springframework.util.concurrent package available since 4.0.

Moreover, they were added for different needs. While the first one provides a base and complete functionality for providing controller's result asynchronously, the second one allows you in addition to bridge your implementation with already existing classes/frameworks, like for example ExecutorService framework (see ListenableFutureTask).

So the bottom line is, use the DeferredResult class when it's enough for you to implement further processing on your own or ListenableFuture when you'd like to use ExecutorService-like frameworks.

like image 171
Milosz Avatar answered Sep 20 '22 12:09

Milosz


DeferredResult is an alternative to Callable that allows you to produce a result. You can also extend DeferredResult to associate additional data or behavior, in case you need to access some data later without needing additional data structures. But that's about it. ListenableFuture future comes in handy when you need to add callbacks to the asynchronous task. Guava's ListenableFuture actually allows for composition, which I don't see Spring's ListenableFuture to do. For that you'd rather use CompletableFuture, which is also supported by Spring. You can compose futures very simply, check this out: http://www.deadcoderising.com/java8-writing-asynchronous-code-with-completablefuture/

like image 35
Ulises Avatar answered Sep 20 '22 12:09

Ulises