FixedThreadPool
使用Executors创建FixedThreadPool时,构造函数如下:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
创建的队列是LinkedBlockingQueue,LinkedBlockingQueue是一个基于链表实现的阻塞队列,默认情况下,该阻塞队列的大小是Integer.MAX_VALUE,由于数值特别大,所以也被称为无界队列。如果使用该线程池执行任务,任务过多就会不断的添加到队列中,任务越多占用的内存就越多,最终有可能会耗尽内存,引起OOM。建议在使用LinkedBlockingQueue时设置队列大小。
SingleThreadExecutor
使用Executors创建SingleThreadExecutor时,构造函数如下:
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
也是使用的LinkedBlockingQueue。
除了可能引起OOM之外,Executors来创建线程池也不能自定义线程的名字,不利于后续分析。所以建议直接使用ThreadPoolExecutor来创建线程池。