Java线程池---processWorkerExit方法解析

/**

  • Performs cleanup and bookkeeping for a dying worker. Called
    • only from worker threads. Unless completedAbruptly is set,
    • assumes that workerCount has already been adjusted to account
    • for exit. This method removes thread from worker set, and
    • possibly terminates the pool or replaces the worker if either
    • it exited due to user task exception or if fewer than
    • corePoolSize workers are running or queue is non-empty but
    • there are no workers.
    • @param w the worker
    • @param completedAbruptly if the worker died due to user exception
      */

开始清理并且标记一个即将销毁的Worker。只有Worker所在的线程会被调用。除非,completedAbruptly被设置(为true)了,说明当前线程是意外停止了,假设Worker总数已经在退出之前重新调整了的。这个方法把当前Worker线程从WorkerSet中移除,并且如果由于用户Task异常导致退出,或者只有少于corePoolSize的Worker正在运行,或者队列并不是空的但是没有Worker的情况下,可能终止整个线程池,或者重新替换Worker。


 private void processWorkerExit(Worker w, boolean completedAbruptly) {
    if (completedAbruptly) // If abrupt, then workerCount wasn't adjusted
        decrementWorkerCount();

    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        completedTaskCount += w.completedTasks;
        workers.remove(w);
    } finally {
        mainLock.unlock();
    }

    tryTerminate();

    int c = ctl.get();
    if (runStateLessThan(c, STOP)) {
        if (!completedAbruptly) {
            int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
            if (min == 0 && ! workQueue.isEmpty())
                min = 1;
            if (workerCountOf(c) >= min)
                return; // replacement not needed
        }
        addWorker(null, false);
    }
}

传入参数:
Worker w:要执行退出的Worker对象
boolean completedAbruptly:是否用户异常退出,true为异常退出。

步骤

  1. 判断是否是意外退出的,如果是意外退出的话,那么就需要把WorkerCount--
  2. 加完锁后,同步将completedTaskCount进行增加,表示总共完成的任务数,并且从WorkerSet中将对应的Worker移除
  3. 调用tryTemiate,进行判断当前的线程池是否处于SHUTDOWN状态,判断是否要终止线程
  4. 判断当前的线程池状态,如果当前线程池状态比STOP大的话,就不处理
  5. 判断是否是意外退出,如果不是意外退出的话,那么就会判断最少要保留的核心线程数,如果allowCoreThreadTimeOut被设置为true的话,那么说明核心线程在设置的KeepAliveTime之后,也会被销毁。
  6. 如果最少保留的Worker数为0的话,那么就会判断当前的任务队列是否为空,如果任务队列不为空的话而且线程池没有停止,那么说明至少还需要1个线程继续将任务完成。
  7. 判断当前的Worker是否大于min,也就是说当前的Worker总数大于最少需要的Worker数的话,那么就直接返回,因为剩下的Worker会继续从WorkQueue中获取任务执行。
  8. 如果当前运行的Worker数比当前所需要的Worker数少的话,那么就会调用addWorker,添加新的Worker,也就是新开启线程继续处理任务。

你可能感兴趣的:(Java线程池---processWorkerExit方法解析)