起因
在查看《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,因此,不合适;
本文探讨了Java中使用线程池的最佳实践,强调避免使用Executors创建线程池,而推荐使用ThreadPoolExecutor来明确控制线程池行为,防止资源耗尽风险。详细解释了FixedThreadPool、SingleThreadPool和CachedThreadPool等预设线程池可能导致的问题。
607

被折叠的 条评论
为什么被折叠?



