通过Executors工具类创建线程池的隐藏风险

最近看了下阿里开发手册,其中有一条写的是通过Executors工具类创建的线程有可能会OOM。因为平时处理多线程问题的时候多以ExecutorService配合Excutors使用,专门查看了下源码,这里记录下加深印象。

通过Executors工具类创建线程池一般有4种方式:

newFixedThreadPool:创建一个有固定线程数的线程池。

newSingleThreadExecutor:创建一个拥有一个线程的线程池。

newCachedThreadPool:创建一个能够根据实际任务数量创建/移除线程的线程池。

ScheduledThreadPoolExecutor:创建一个能够定时执行的线程池。

事实上,以上这四种线程池最终都是通过以下方式进行线程池的初始化:

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

通过ThreadPoolExcutor类构造的线程池中有两个重要的参数:

maximumPoolSize:线程池中所能够维持的最大线程数

workQueue:用于存储待处理的任何的队列

事实上,只要这两个参数足够大,即潜在的线程数量足够多或者待处理的task数量足够多则有可能发生OOM。而上述四种线程池的创建方式则为OOM提供了潜在的可能。

newFixedThreadPool 及 newSingleThreadExecutor

newFixedThreadPool 及 newSingleThreadExecutor的创建方式允许待处理的tasks数量为Integer.MAX_VALUE:

    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>()));
    }

这里的LinkedBlockingQueue的构造方法是:

    public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE);
    }
    public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }

即创建了一个容量为Integer最大值的待处理队列,即我们可以在当前线程池中放入相当数量的tasks而当任何足够多的时候有可能出现OOM。

newCachedThreadPool 及 ScheduledThreadPoolExecutor

newCachedThreadPool 及 ScheduledThreadPoolExecutor

newCachedThreadPool 及 ScheduledThreadPoolExecutor允许创建创建最多Integer.MAX_VALUE个线程数:

    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }

因此这里理论上当创建的线程数足够多的时候也有可能报OOM。

因此,总结下来,通过Excutors工具类创建线程池的时候需要结合实际场景。通过程序控制好待处理任务的数量以及可能创建的线程数,Excutors工具类仍旧是十分好用的线程工具类。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值