Spring MVC异步支持与Spring WebFlux有何差异?异步机制解析
Hey there! Let me walk through how async request handling works in Spring MVC (feel free to chime in if I miss anything):
When you run a Spring MVC app on a server like Tomcat, the server provides a thread pool to handle incoming requests. Each request gets picked up by a thread from this pool, and that thread stays tied to the request until the entire processing is done.
The big downside here? If your request involves a time-consuming task (like calling a slow external API, heavy database query, or file processing), that thread will be stuck in a busy state the whole time. Too many such slow requests can quickly exhaust the thread pool, leaving no threads available for new incoming requests—killing your app's throughput.
To avoid this bottleneck, you can change your controller method's return type from a synchronous one (like String, ModelAndView, or a DTO) to an asynchronous type like Callable<String> or DeferredResult<String>. Here's how each works:
Using
Callable<String>
When your controller returns aCallable, the Tomcat worker thread doesn't wait for the task to finish. Instead, it hands off theCallableexecution to Spring'sTaskExecutor(a separate thread pool managed by Spring), then immediately releases itself back to Tomcat's thread pool. Once theCallablecompletes its work, Spring will grab another thread (either from Tomcat's pool or its own) to send the response back to the client.Using
DeferredResult<String>
This gives you even more control. WithDeferredResult, you can offload the task to any thread pool you want—whether it's a custom one you've configured, or even a thread from an external service. The Tomcat worker thread releases right after the controller returns theDeferredResult, and your app can take its time processing the task. Once the result is ready, you just calldeferredResult.setResult(yourData), and Spring will trigger the response handling using an available thread.
By using these async return types, you free up Tomcat's worker threads much faster. This lets your server handle far more concurrent requests without getting blocked by slow tasks—huge win for scalability!
内容的提问来源于stack exchange,提问作者Almas Abdrazak

