To understand what DeferredResult does, you need to understand the Async concept from Servlet 3.0.
Using Servlet 3.0, you can take AsyncContext from the request, save it as a collection.
AsyncContext aCtx = request.startAsync(request, response);
as a result, your Application Container Thread will be released.
Do some operation in a separate thread and return the result to the Servlet response:
aCtx.getResponse().getWriter().print(result);
From this point on, your DeferredResult works exactly the same.
A small example:
Now think that every 5 seconds you get a quote from a third-party service. And you have clients who examine each server for a long time to update something.
You have your controller method:
@RequestMapping(value="/getQuote.do", method=RequestMethod.GET) @ResponseBody public DeferredResult<String> getQuote(){ final DeferredResult<String> deferredResult = new DeferredResult<String>(); someMap.put(deferredResult); return deferredResult; }
Now you can see the method outside the controller, which receives a quote and returns a response to the client.
function getQuoteAndUpdateClients(){ String quote = getUpdatedQuoteFromThirdPartyService(); for (DeferredResult<String> deferredResult: someMap){ deferredResult.setResult(quote); } }
danny.lesnik
source share