为什么在创建 ThreadPoolTask​​Executor 时不抛出 IllegalArgumentException?

时间:2021-04-23 06:30:15

标签: spring-boot threadpoolexecutor

我创建了一个实现 AsyncConfigurer 的配置

@EnableAsync
@Component
public class AsyncExecutorConfig implements AsyncConfigurer {

    private final int poolSize;
    private final int queueCapacity;
    private final int maxPoolSize;

    @Autowired
    public AsyncExecutorConfig(@Value(PropertyNames.ASYNC_POOL) int poolSize,
    @Value(PropertyNames.QUEUE_SIZE) int queueCapacity,
    @Value(PropertyNames.MAX_POOL_SIZE) int maxPoolSize
    ) {
        this.poolSize = poolSize;
        this.queueCapacity = queueCapacity;
        this.maxPoolSize = maxPoolSize;
    }

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(poolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix("demo-async-");
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }
}

但我不明白一件事。在 Spring Boot 版本 1.5.2.RELEASE 中使用相同的配置时,核心池大小为 100 ,最大池大小为 50。由于核心池大小 > 最大池大小,我得到一个 IllegalArgumentException 异常。当我调试时, getAsyncExecutor 方法被调用。

但是当我在 Spring Boot 2.2.2.RELEASE 中使用相同的配置和相同的池大小时,getAsyncExecutor 方法不会被调用,我也不会得到 IllegalArgumentException 和程序运行正常。

@Async 方法确实有效。但我对配置是如何进行的感到困惑。

<块引用>

更新

我翻遍了整个日志,发现在Spring Boot 2中,执行器服务的初始化发生在需要的时候(我的假设是懒惰的)。但怎么会这样?

在 Spring Boot 1 中,初始化发生在流程的早期。

0 个答案:

没有答案