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?
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:
org.springframework.web.context.request.async
package added in version 3.2.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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With