动态线程池的setCorePoolSize
等方法动态调整逻辑深入分析
1. 整体架构设计
动态线程池框架采用了适配器模式和观察者模式的设计,核心组件包括:
- DtpRegistry: 线程池注册中心,管理所有线程池实例
- ExecutorAdapter: 适配器接口,统一不同类型线程池的操作
- AbstractRefresher: 配置刷新器,监听配置变更
- VariableLinkedBlockingQueue: 支持动态容量调整的队列
2. 核心动态调整逻辑
2.1 doRefreshPoolSize
方法 - 线程池大小调整的核心逻辑
private static void doRefreshPoolSize(ExecutorAdapter<?> executor, DtpExecutorProps props) {
if (props.getMaximumPoolSize() < executor.getMaximumPoolSize()) {
if (!Objects.equals(executor.getCorePoolSize(), props.getCorePoolSize())) {
executor.setCorePoolSize(props.getCorePoolSize());
}
if (!Objects.equals(executor.getMaximumPoolSize(), props.getMaximumPoolSize())) {
executor.setMaximumPoolSize(props.getMaximumPoolSize());
}
return;
}
if (!Objects.equals(executor.getMaximumPoolSize(), props.getMaximumPoolSize())) {
executor.setMaximumPoolSize(props.getMaximumPoolSize());
}
if (!Objects.equals(executor.getCorePoolSize(), props.getCorePoolSize())) {
executor.setCorePoolSize(props.getCorePoolSize());
}
}
关键设计思想:
- 解决JDK-7153400 Bug:确保
corePoolSize ≤ maximumPoolSize
,避免IllegalArgumentException
- 智能调整顺序:
- 当新的
maximumPoolSize
小于当前值时:先调整cor
- 当新的