Executors弊端

Executors.newFixedThreadPool(1);  // LinkedBlockingQueue  无界的队列    可能会导致内存溢出

Executors.newCachedThreadPool(); // maximumPoolSize 使用了最大值,可能会导致内存溢出
Executors 和 ThreadPoolExecutor 在创建线程池方面存在多方面的区别: - **定制化程度**:Executors 仅提供三种常用的创建方式,资源配置参数为默认设置,无法满足定制化线程池的需求;而 ThreadPoolExecutor 则更为灵活,能满足定制化需求,因为它实现了 Executors 常用的三种创建方法,且可以通过构造函数来自行指定参数 [^1]。 - **实现关系**:Executors 类下的 newFixedThreadPool、newScheduledThreadPool、newSingleThreadExecutor、newCachedThreadPool 底层均由 ThreadPoolExecutor 实现 [^2]。 - **风险问题**:《阿里巴巴 Java 开发手册》不允许使用 Executors 创建线程池,而是推荐使用 ThreadPoolExecutor。Executors 各方法存在弊端,如 newFixedThreadPool 和 newSingleThreadExecutor 堆积的请求处理队列可能耗费大量内存,甚至导致 OOM;newCachedThreadPool 和 newScheduledThreadPool 线程数最大可达 Integer.MAX_VALUE,可能创建大量线程,同样会引发 OOM。而 ThreadPoolExecutor 创建线程池只有通过构造函数这一种方式,可自行指定参数,能让开发者更明确线程池的运行规则,规避资源耗尽的风险 [^3]。 ### 代码示例 以下是使用 Executors 和 ThreadPoolExecutor 创建线程池的简单示例: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolExample { public static void main(String[] args) { // 使用 Executors 创建线程池 ExecutorService executorService = Executors.newFixedThreadPool(5); // 使用 ThreadPoolExecutor 创建线程池 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 2, // 核心线程数 5, // 最大线程数 60L, // 线程空闲时间 TimeUnit.SECONDS, new java.util.concurrent.LinkedBlockingQueue<>(10) // 任务队列 ); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值