JDK1.8源码分析笔记-ThreadPoolExecutor

1. 线程池的创建

通过Executors类的工厂方法创建线程池

// 获取指定线程池大小的线程池
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue(),
                                      threadFactory);
    }
    
// 获取只有一个线程的线程池
// 此线程池适合使用在异步串行任务列队的业务场景中
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue()));
    }

// 获取一个缓存线程池
public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue());
    }

可以看到上述3个线程池创建的工厂方法中都使用了相同的构造函数

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue 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;
    }

2. 执行任务

public void execute(Runnable command) 

在进入execute方法内部之前我们先看看在创建线程池时创建的对象ThreadPoolExecutor。

在其中有这样一段定义

// runState is stored in the high-order bits
    private static final int RUNNING    = -1 << COUNT_BITS;
    private static final int SHUTDOWN   =  0 << COUNT_BITS;
    private static final int STOP       =  1 << COUNT_BITS;
    private static final int TIDYING    =  2 << COUNT_BITS;
    private static final int TERMINATED =  3 << COUNT_BITS;

这些常量定义了ThreadPoolExecutor执行的状态

  • RUNNING — 运行状态,可以添加新任务,也可以处理阻塞队列中的任务
  • SHUTDOWN — 待关闭状态,不再接受新的任务,会继续处理阻塞队列中的任务
  • STOP — 停止状态,此时的线程池不处理任何任务
  • TIDYING — 整理状态,也可以理解为预终结状态,这个时候任务都处理完毕,池中无有效线程
  • TERMINATED — 终止状态

理解了线程池是有生命周期后再来看任务提交方法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. 判断有效线程数是否小于核心线程数
    if (workerCountOf(c) < corePoolSize) {
        // 创建新线程
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    // 2. 首先判断当前的线程池是否是处于 RUNNING 状态,只有 RUNNING 状态才可以接收新任务。接着判断能否成功添加到阻塞队列,如果队列满了或者其他情况则会跳转到下一步
    if (isRunning(c) && workQueue.offer(command)) {
        // 再次检查线程池的状态,如果进入了非 RUNNING 状态,回滚队列,扔掉这个任务
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command);
        // 如果处于 RUNNING 状态则检查当前的有效线程,如果没有则创建一个线程
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    // 3. 前两步失败了,就强行创建线程,成功会返回true,如果失败扔掉这个任务
    else if (!addWorker(command, false))
        reject(command);
}
JDK1.8源码分析笔记-ThreadPoolExecutor_第1张图片
ThreadPoolExecutor源码分析.jpg

3. 创建工作线程

在execute方法中出现最多的是addWorker方法

3.1 异常校验

private boolean addWorker(Runnable firstTask, boolean core) {
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);
        // Check if queue empty only if necessary.
        // 检查线程池状态,firstask,以及队列状态,
        // 转换一下判断逻辑会舒服很多
        // rs >= SHUTDOWN && (rs != SHUTDOWN || firstTask != null || workQueue.isEmpty())
        // 总结起来就是 当前处于非 RUNNING 状态,并且是下面三种情况中的一个
        // 1. 不是处于 SHUTDOWN 状态
        // 2. 有新的任务
        // 3. 阻塞队列中没有任务
        // 则直接跳出
        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
        }
    }
  }

3.2 创建线程

// 标记 worker 开启状态
boolean workerStarted = false;
// 标记 worker 添加状态
boolean workerAdded = false;
Worker w = null;
try {
    // 将这个任务作为 worker 的第一个任务传入
    w = new Worker(firstTask); 
    // 通过 worker 获取到一个线程
    final Thread t = w.thread;
    if (t != null) {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            // Recheck while holding lock.
            // Back out on ThreadFactory failure or if
            // shut down before lock acquired.
            int rs = runStateOf(ctl.get());
            
            // running状态,或者 shutdown 状态但是没有新的任务
            if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) {
                if (t.isAlive()) // precheck that t is startable
                    throw new IllegalThreadStateException();
                // 将这个 worker 添加到线程池中
                workers.add(w); 
                int s = workers.size();
                if (s > largestPoolSize)
                    largestPoolSize = s;
                // 标记worker添加成功
                workerAdded = true;
            }
        } finally {
            mainLock.unlock();
        }
        // 如果 worker 创建成功,开启线程
        if (workerAdded) {
            t.start();
            workerStarted = true;
        }
    }
} finally {
    if (! workerStarted)
        addWorkerFailed(w);
}
return workerStarted;

3.3 Worker

Worker 是 ThreadPoolExecutor 的一个内部类继承自 AbstractQueuedSynchronizer,持有线程对象和任务对象,实现了 Runnable 接口。
AbstractQueuedSynchronizer实现了

private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
        /**
         * This class will never be serialized, but we provide a
         * serialVersionUID to suppress a javac warning.
         */
        private static final long serialVersionUID = 6138294804551838833L;

        /** Thread this worker is running in.  Null if factory fails. */
        final Thread thread;
        /** Initial task to run.  Possibly null. */
        Runnable firstTask;
        /** Per-thread task counter */
        volatile long completedTasks;

        /**
         * Creates with given first task and thread from ThreadFactory.
         * @param firstTask the first task (null if none)
         */
        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

        /** Delegates main run loop to outer runWorker  */
        public void run() {
            runWorker(this);
        }

        // 此处省去Lock methods代码...
    }

线程启动会执行

runWorker(this);
final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

上述代码中除了一些异常判断和加锁外最重要的一个调用是getTask()。

我们来看一下getTask()内部细节

private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?

        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

核心调用为

Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();

调用poll或者take方法从阻塞列队中取出未执行的任务。

尾巴

通过源码的学习发现一些实现方式与我初期设想的概念有很大不同(自己还是too young too simple)。

  1. 首先执行execute方法提交任务后不是我想象中的将任务交付给线程来执行,而是由工作线程来从阻塞列队中挑选task进行执行。
  2. 引入核心线程数的概念,这样在线程池闲置的时候可以有效降低资源的开销。由于工作线程worker有可能会在执行任务中异常中断或者未能取到任务而被释放,所以核心线程数不是最早创建的线程,它是以数量来区分核心还是非核心。

举例说明:线程池中的线程在执行完任务后会去从阻塞列队取出下一个任务开始执行
从阻塞列队中取任务有两个方法:

1. take(方法没有超时时间,会一直阻塞直到取出入队的数据)
2. poll(方法取任务会有超时时间,超过时间则返回null)

线程在取任务的时候,线程池会比较当前的有效线程数和允许的核心线程数,如果小于当前的核心线程数则使用第一个方法取任务,也就是没有超时回收,如果大于核心线程数,则使用第二个,一旦超时就回收,所以,并没有绝对的核心线程,只要这个线程出于闲置状态就有被回收的可能。

还有一种情况是设置了线程池允许核心线程超时回收,那么无论线程数有多少,统统会使用第二个方法取任务。
使用poll方法获取任务在超时后工作线程会结束并释放。

在研究代码时还发现了LinkedBlockingQueueSynchronousQueueAbstractQueuedSynchronizer
相关源码的详细解读会在接下来的深入学习JDK中进行。

你可能感兴趣的:(JDK1.8源码分析笔记-ThreadPoolExecutor)