线程池不允许使用Executors去创建,而是通过使用ThreadPoolExecutor的方式更能明白线程池的运行规则,规避资源耗尽的风险
使用Executors的弊端:
-
根据Executors创建的这两个线程池newFixedThreadPool和newSingleThreadExecutor。我们可以注意到使用的都是LinkedBlockingQueue,并且是没有添加参数的,这就意味着允许请求队列长度为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>()));
}
2.而这个newCachedThreadPool则是让最大线程数设置为了Integer.MAX_VALUE,可能会导致创建大量的线程从而导致OOM
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}