Spring @Async 中的默认值是什么?

What are the defaults in Spring @Async?

你能告诉我 Spring @Async ThreadPoolTaskExecutor 的默认参数是什么吗?或者我怎样才能自己找到它们?

maxPoolSize、corePoolSize 和 queueCapcity 的默认值是多少?

我应该覆盖它们以改进我的应用程序还是使用默认值就可以了?

关于 ThreadPoolTaskExecutor 的实施。您可以在他们的 github 存储库中查看它。 ThreadPoolTaskExecutor

private int corePoolSize = 1;

private int maxPoolSize = Integer.MAX_VALUE;

private int queueCapacity = Integer.MAX_VALUE;

我假设您想使用 @EnableAsync (javadoc) 注释来支持 spring.

中的异步任务执行

在这种情况下,文档说明如下:

默认情况下,Spring 将搜索关联的线程池定义: 上下文中唯一的 org.springframework.core.task.TaskExecutor bean,否则是名为 "taskExecutor" 的 java.util.concurrent.Executor bean。

如果两者都不可解析,将使用org.springframework.core.task.SimpleAsyncTaskExecutor来处理异步方法调用。

现在,如果您想提供自己的定制,您可以定义(实施)一个 AsyncConfigurerjavadoc),它基本上允许定义执行程序和异常处理程序(超出此范围)问题)。

根据 Spring 消息来源 @EnableAsync 注释配置 SimpleAsyncTaskExecutor 并且不重用线程,任何时候使用的线程数默认情况下不受限制。

提交作业的进程和线程池之间有一个队列。如果所有线程都被占用,则作业只会排队。如果队列满了,线程也被占用了,那么新的任务就会被拒绝。您可以选择几种拒绝策略(例如,呼叫者运行)。

如果您正在寻找真正的池化,请查看 SimpleThreadPoolTaskExecutorThreadPoolTaskExecutor

@Async 使用的任务执行器的 bean 名称是 applicationTaskExecutor

applicationTaskExecutor 的属性在 TaskExecutionProperties

中定义
private int queueCapacity = Integer.MAX_VALUE;
private int coreSize = 8;
private int maxSize = Integer.MAX_VALUE;

我认为您需要 @EnableAsync 才能启用 @Async 注释,此注释将使用默认实现 SimpleAsyncTaskExecutor

SimpleAsyncTaskExecutor 实现不重用任何线程,而是为每次调用启动一个新线程。但是,它确实支持并发限制,该限制将阻止任何超过限制的调用,直到释放插槽为止。

你可以定义你自己的ThreadPoolTaskExecutor喜欢

@Configuration
public class ThreadConfig {

    @Bean("otherExecutor")
    public TaskExecutor threadPoolTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(16);
        executor.setMaxPoolSize(32);
        executor.initialize();

        return executor;
    }
}

并在@Async

中参考这个
@Async("otherExecutor")
void doSomething(String s) {
    // this will be executed asynchronously by "otherExecutor"
}

定义于TaskExecutionProperties. Autoconfigure uses this file instead of ThreadPoolTaskExecutor as mentioned in