Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kamzrk/b4a868642aab4840b1e73bf9ca688a32 to your computer and use it in GitHub Desktop.
Save kamzrk/b4a868642aab4840b1e73bf9ca688a32 to your computer and use it in GitHub Desktop.
Using the DeferredResult Class in Spring (Non-blocking Java Servlet Controller Methods in Spring)
GetMapping("/async-deferredresult")
public DeferredResult<ResponseEntity<?>> handleReqDefResult(Model model) {
LOG.info("Received async-deferredresult request");
DeferredResult<ResponseEntity<?>> output = new DeferredResult<>(); //just a declaration
ForkJoinPool.commonPool().submit(() -> { //we pass a service method to an ExecutorService / thread pool
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
}
output.setResult(ResponseEntity.ok("ok")); //this service deals with the DeferredResult object declared earlier
});
LOG.info("servlet thread freed"); //we free the servlet thread
return output; //we send a "promise" of the expected output from the service called in a separate thread
}
//We can additionally register some callbacks:
deferredResult.onCompletion(() -> LOG.info("Processing complete"));
deferredResult.onTimeout(new Runnable() {
@Override
public void run() {
deferredResult.setErrorResult(
ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT).body("Request timeout occurred."));
}
});
deferredResult.onError((Throwable t) -> {
deferredResult.setErrorResult(
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred."));
});
//Takeaway:
/*
In above example, the request is processed in a separate thread. This approach carries the following advantages.
Http worker threads released immediately by passing on the work to the non HTTP thread.
The worker threads are able to handle additional HTTP request without waiting for the long-running process to finish the work.
*/
/*
The DeferredResult class provide the following three callbacks
onComletion – block on execute when the request completes.
onTimeout – Custom code to invoke once timeout occurs.
onError – Execute code on error.
*/
//vide: https://www.baeldung.com/spring-deferred-result
//vide: https://www.javadevjournal.com/spring-mvc/spring-deferred-result/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment