ExecutorService有下面几种创建方式
Executors.newCachedThreadPool();
Executors.newFixedThreadPool()
Executors.newScheduledThreadPool()
Executors.newSingleThreadExecutor()
Executors.newSingleThreadScheduledExecutor()
抽取其中一个方法查看源码:
publicstatic ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads,nThreads,
0L, TimeUnit.MILLISECONDS,
newLinkedBlockingQueue<Runnable>());
}
/**
* Creates a {@code LinkedBlockingQueue}with a capacity of
* {@link Integer#MAX_VALUE}.
*/
publicLinkedBlockingQueue(){
this(Integer.MAX_VALUE);
}
/**
* A constant holding the maximum value an{@code int} can
* have, 2<sup>31</sup>-1.
*/
public static final int MAX_VALUE = 0x7fffffff;
由上面的方法参数知道,Executors创建的ExecutorService并不能设置控制消息队列的长列,默认长度是2^31,当线程处理速度较慢且并发任务太多时,任务队列的任务将不断堆积,就可能引起OOM。因此建议直接
ThreadPoolExecutor executor = new TThreadPoolExecutor(int corePoolSize,
intmaximumPoolSize,
longkeepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
这样就可以灵活定制队列,建议使用new ThreadPoolExecutor。
探讨了Java中ExecutorService的不同创建方式及默认配置可能导致的问题。推荐使用ThreadPoolExecutor以更好地控制线程池和任务队列。
1390

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



