本文详解 spring boot 2.x 集成 undertow 时的默认线程配置(io 线程数与工作线程数),提供运行时获取方式、配置原理及自定义建议。
本文详解 spring boot 2.x 集成 undertow 时的默认线程配置(io 线程数与工作线程数),提供运行时获取方式、配置原理及自定义建议。
在 Spring Boot 2.0.8.RELEASE(搭配 Undertow 1.4.2)中,嵌入式 Undertow 服务器的线程模型由两个关键参数控制:IO 线程数(io-threads) 和 工作线程数(worker-threads)。需注意:Undertow 并不使用传统“任务队列 + 拒绝策略”的线程池模型(如 ThreadPoolExecutor 的 queueSize),其 worker-threads 对应的是基于 XNIO 的无界工作线程池,不存在显式的“线程队列大小”配置项;实际任务调度由 XNIO 的 Worker 负责,任务以事件形式直接分发至空闲工作线程,无需排队等待。
默认值遵循以下规则:
- io-threads:默认为 CPU 核心数(Runtime.getRuntime().availableProcessors());
- worker-threads:默认为 io-threads × 8(即 CPU 核心数的 8 倍),最小值为 20。
可通过 UndertowServletWebServerFactory 的构建器在启动时动态读取这些值:
import org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UndertowConfig {
@Bean
public UndertowWebServerFactoryCustomizer undertowWebServerFactoryCustomizer() {
return factory -> {
int ioThreads = factory.getBuilder().getIoThreads();
int workerThreads = factory.getBuilder().getWorkerThreads();
System.out.println("Default IO thread count: " + ioThreads);
System.out.println("Default worker thread count: " + workerThreads);
};
}
}运行后,典型输出如下(以 4 核机器为例):
Default IO thread count: 4 Default worker thread count: 32
⚠️ 注意事项:
- 不要尝试通过 setQueueSize() 或类似方法设置“队列大小”——Undertow/XNIO 的 Worker 不暴露该配置,强行调用会抛出 UnsupportedOperationException;
- 若需调整,默认值已针对高吞吐场景优化,仅在明确压测瓶颈(如大量长连接或 CPU 密集型阻塞操作)时才建议自定义;
- 自定义方式推荐使用 application.yml(更简洁、可环境隔离):
server:
undertow:
io-threads: 8
worker-threads: 64或通过 Java Config 显式设置:
@Bean
public UndertowServletWebServerFactory undertowServletWebServerFactory() {
UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
factory.addAdditionalUndertowBuilderCustomizers(builder -> {
builder.setIoThreads(8);
builder.setWorkerThreads(64);
});
return factory;
}总结:理解 Undertow 的线程模型本质(事件驱动 + XNIO Worker)比纠结“队列大小”更重要。优先依赖默认配置,结合监控(如 ThreadPoolTaskExecutor 指标、JVM 线程 dump)验证实际负载表现,再按需微调 io-threads 和 worker-threads。










