You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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):

Default Request Handling in Spring MVC

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.

Fixing It: Switch to Async Return Types

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 a Callable, the Tomcat worker thread doesn't wait for the task to finish. Instead, it hands off the Callable execution to Spring's TaskExecutor (a separate thread pool managed by Spring), then immediately releases itself back to Tomcat's thread pool. Once the Callable completes 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. With DeferredResult, 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 the DeferredResult, and your app can take its time processing the task. Once the result is ready, you just call deferredResult.setResult(yourData), and Spring will trigger the response handling using an available thread.

Key Benefit

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:31:54