0 day streak
java / expert
Snippet

Asynchronous Request Processing using DeferredResult

DeferredResult allows freeing up servlet threads while waiting for a background task to complete. This improves scalability for long-running I/O operations by avoiding thread starvation.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
@GetMapping("/process")
public DeferredResult<ResponseEntity<String>> processAsync() {
DeferredResult<ResponseEntity<String>> result = new DeferredResult<>(10000L);
CompletableFuture.supplyAsync(() -> longRunningTask())
.thenAccept(res -> result.setResult(ResponseEntity.ok(res)))
.exceptionally(ex -> {
result.setErrorResult(ResponseEntity.status(500).body("Failed"));
return null;
});
return result;
}
spring
Breakdown
1
new DeferredResult<>(10000L)
Creates a result holder with a specific timeout in milliseconds.
2
result.setResult(...)
The method that actually sends the final response to the client once the background work is done.