为什么企业内部都不推荐使用内置的线程池而使用ThreadPoolExecutor构造方法去生成线程池
先说结论!!!!!!!
其实,因为使用内置方法创建线程池的时候会造成OOM情况
比如newFixedThreadPool和singleThreadPool,它初始化的阻塞队列的长度是Integer.MAX_VALUE,这样会导致很多任务会被放到阻塞队列中等待核心线程的调用,这样可能会导致OOM的情况
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
而newCacheThreadPool和newSchedualedThreadPool,这两个方法在调用的时候将最大线程数设置为Integer.MAX_VALUE,这样当没有达到最大线程数的阈值的话,就会不断创建非核心线程去执行任务,这样时间长了可能也会导致OOM
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
创作不易,希望大家能够点个赞,也希望大家能帮忙指出问题,一起进步!!!谢谢大家~~