起因
在查看《Java开发手册(泰山版)》发现这么一段话:
【强制】线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors返回的线程池对象的弊端如下:
1)FixedThreadPool和SingleThreadPool:
允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致OOM。
2 CachedThreadPool:
允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致 OOM。
为什么SingleThreadPool/FixedThreadPool不行?
public static ExecutorService newFixedThreadPool(int nThreads) { public static ExecutorService newSingleThreadExecutor() { |
我们继续跟踪LinkedBlockingQueue的构造方法:
public LinkedBlockingQueue() { |
由此可以看出,这个LinkedBlockingQueue默认深度是Integer.MAX_VALUE;
为什么CachedThreadPool不行?
public static ExecutorService newCachedThreadPool() { public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { |
这里ThreadPoolExecutor的第2个参数是maximumPoolSize,而调用的时候传入的是Integer.MAX_VALUE,因此,不合适;