0 day streak
java / expert
Snippet

Non-Blocking Asynchronous Processing with DeferredResult

DeferredResult is used to release the web container thread while processing long-running tasks in a separate thread. This significantly improves application scalability and throughput under high load.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@GetMapping("/async-task")
public DeferredResult<ResponseEntity<?>> executeAsyncTask() {
DeferredResult<ResponseEntity<?>> output = new DeferredResult<>(5000L);
ForkJoinPool.commonPool().submit(() -> {
try {
// Simulate heavy computation
Thread.sleep(2000);
output.setResult(ResponseEntity.ok("Task Completed"));
} catch (Exception e) {
output.setErrorResult(ResponseEntity.status(500).body("Error"));
}
});
return output;
}
spring
Breakdown
1
DeferredResult<ResponseEntity<?>> output = new DeferredResult<>(5000L);
Initializes a DeferredResult with a 5-second timeout.
2
output.setResult(ResponseEntity.ok("Task Completed"));
Sets the final result of the operation, which completes the HTTP response.
3
return output;
Immediately returns the container thread to the pool while the worker thread continues processing.