@Async 的两个注意事项

例子:

@Async
public void test() {
    log.info("test");
}
复制代码

没有使用Spring Boot

打个断点可知,默认使用的是org.springframework.core.task.SimpleAsyncTaskExecutor

image.png

这个玩意如其名,很简陋,观察源码,起执行方法:每次执行都会新增一个线程,在并发高的情况下会无限创建线程,后果可想而知

protected void doExecute(Runnable task) {
    Thread thread = this.threadFactory != null ? this.threadFactory.newThread(task) : this.createThread(task);
    thread.start();
}
复制代码

使用Spring Boot

org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration 会帮你自动配置org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor (spring boot 2才有)

但是这个线程池所用的队列是LinkedBlockingQueue,是一个无界队列,在并发高的时候,所有任务进入队列,很可能导致内容溢出

正确使用

根据业务情况自定义线程池:www.cnblogs.com/duanxz/p/60…

猜你喜欢

转载自juejin.im/post/7078544630614065188