ThreadPoolExecutor中corePoolSize、maximumPoolSize及workQueue容量的关系

1.corePoolSize、maximumPoolSize关系
ThreadPoolExecutor的构造方法如下:

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

结论:从ThreadPoolExecutor的构造方法可以看出,maximumPoolSize 不能小于 corePoolSize。

2.corePoolSize、maximumPoolSize及workQueue容量的关系
execute方法如下:

 public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        // 1. 如果当前线程数 小于 corePoolSize,则尝试添加新线程
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
            // 添加成功,不会往下走
                return;
            c = ctl.get();
        }
        // 2. 尝试向workQueue添加队列(offer方法在workQueue没有容量时,添加失败),线程已经存在不会创建新的线程,如果不存在则创建新的线程。
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        // 3. 添加新线程,此处会比较maximumPoolSize,如果大于maximumPoolSize,则会使用饱和策略
        else if (!addWorker(command, false))
        // 4.执行饱和策略
            reject(command);
}

addWorker方法如下,省略添加逻辑:

private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
				// 如果当前线程数 >= 最大容量,则添加失败
                if (wc >= CAPACITY ||
				// 如果当前线程数大于等于核心线程或最大线程池数,则添加失败
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        // 略...
    }

备注CAPACITY 为536870911,所以,对于wc >= CAPACITY,一般线程数也不会有那么大,此处可忽略。

结论:
从execute方法和addWorker方法可以看出,当前线程数优先与corePoolSize 比较,大于corePoolSize ,则与workQueue容量比较;
如果当前线程数大于workQueue容量,则与maximumPoolSize比较;
如果当前线程数大于maximumPoolSize,则执行饱和策略;
最后,根据饱和策略做出相应的处理。

3.饱和策略如下:
Abort策略:默认策略,新任务提交时直接抛出未检查的异常RejectedExecutionException,该异常可由调用者捕获。
CallerRuns策略:为调节机制,既不抛弃任务也不抛出异常,而是将某些任务回退到调用者。不会在线程池的线程中执行新的任务,而是在调用exector的线程中运行新的任务。
Discard策略:新提交的任务被抛弃。

参考

[1]java线程池的核心线程数与最大的线程数的区别,饱和策略

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值