不管是阿里,还是华为java开发手册,都会有一条建议,就是让开发者不要使用Executors去创建线程池,而是使用构造函数ThreadPoolExecutor的方式来创建,并设置合理的参数。原因如下:
说明:Executors 返回的线程池对象的弊端如下:
1) FixedThreadPool 和 SingleThreadPool:
允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
2) CachedThreadPool:
允许的创建线程数量为 Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。
在spring框架中,spring提供了ThreadPoolTaskExecutor来创建线程池,该类在spring-context包下。其实ThreadPoolTaskExecutor是对ThreadPoolExecutor的封装。
到了springboot这里,因为引入了spring-boot-autoconfigurer,自动装配机制,在task包下,直接把ThreadPoolTaskExecutor注入到bean容器里面。所以在springboot项目中,如果要使用线程池,可以直接使用,都不用额外任何配置。
springboot自动装配的线程池使用的配置如下:
默认核心线程数是8个。最大线程数和等待队列都是Integer.MAX_VALUE。综合上面的介绍,默认配置的线程池其实也有OOM的风险。
这里使用的springboot版本是2.7.8。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springexample</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.8</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<gr