描述
线程池不允许使用Executors 去创建,而是通过ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors 返回的线程池对象的弊端如下:
1)FixedThreadPool 和SingleThreadPool 允许的请求队列长度为Integer.MAX_VALUE ,可能会堆积大量的请求,从而导致OOM 。
2)CachedThreadPool 和ScheduledThreadPool 允许的创建线程数量为Integer.MAX_VALUE ,可能会创建大量的线程,从而导致OOM 。
错误代码
Executors executors = new FixedThreadPool(int nThreads);
Executors executors = new SingleThreadPool(int nThreads);
解决方法
ThreadPoolExecutor mThreadPool = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, 0L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
mThreadPool.submit();