ThreadPoolExecutor线程池原理以及源码分析

2019-05-01  本文已影响0人  无聊之园

线程池流程:

线程池核心类:
ThreadPoolExecutor:普通的线程池
ScheduledThreadPoolExecutor: 延时重复执行线程池。暂不研究
ForkJoinPool:fork join分片合并线程池。暂不研究
Executors:线程池工具类,提供了6中线程池工具方法:
1.newFixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

返回ThreadPoolExecutor对象,核心线程数和最大线程数相等,堵塞队列为LinkedBlockingQueue,大小没有限制,意味着,当核心线程数满了之后,一直往堵塞队列添加任务,知道Integer.MAX_VALUE。故在一定条件下,会占用很多内存。

2.newCachedThreadPool

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

返回ThreadPoolExecutor对象,核心线程数为0, 最大线程数为Integer.MAX_VALUE, 线程空闲时间为60秒,堵塞队列为同步队列,SynchronousQueue队列的put和take是互相唤醒的,但是线程池execute提交任务调用的是offer方法,offer方法不会堵塞,能添加进去则添加进去(只有其他线程正在poll堵塞在那,才可能offer进去),不能则马上返回然后启动一个线程执行,线程获取任务调用的是poll方法,因为poll方法可以设定超时时间,来达到超时60秒就返回线程结束的机制,而take方法没有超时机制。
再一定条件下,可能会产生很多个线程,占用大量的资源。

3.newScheduledThreadPool

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
       return new ScheduledThreadPoolExecutor(corePoolSize);
   }

暂不研究
4.newSingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

newFixedThreadPool的单线程版
5.newSingleThreadScheduledExecutor

public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
        return new DelegatedScheduledExecutorService
            (new ScheduledThreadPoolExecutor(1));
    }

暂不研究
6.newWorkStealingPool

public static ExecutorService newWorkStealingPool() {
        return new ForkJoinPool
            (Runtime.getRuntime().availableProcessors(),
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    }

暂不研究。

ThreadPoolExecutor源码分析

内部类

image.png
总共有5个内部类,前面4个是拒绝任务策略,最后一个是实际执行任务的线程子类。
4个拒绝任务策略类都很简单:
AbortPolicy:直接报错。
CallerRunsPolicy:如果线程池正在运行,则执行掉抛弃的任务。
DiscardOldestPolicy:如果线程池正在运行,则抛弃堵塞队列的头部最先进堵塞队列的任务,重新提交任务。
DiscardPolicy: 抛弃任务,什么都不做
真正执行任务的类:
work:
/** 父类位AQS类,实现了tryAcquire和tryRelease方法,能够同步锁住资源。
* 实现了runnable接口,所以可以直接new Thread(worker)进行线程执行。
**/
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. */
        // 执行自身work任务的线程引用
        final Thread thread;
        /** Initial task to run.  Possibly null. */
        // 线程当前执行的任务,firstTask任务,会从堵塞队列中不停的取
        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;
            // 指定的线程factory创建线程,传入了work本身,
          //所以这个线程start的时候,执行的就是work的run方法
            this.thread = getThreadFactory().newThread(this);
        }

        /** Delegates main run loop to outer runWorker  */
        public void run() {
            // 真正开启线程,循环从堵塞队列中取任务执行
            runWorker(this);
        }

        // Lock methods
        //
        // The value 0 represents the unlocked state.
        // The value 1 represents the locked state.

        protected boolean isHeldExclusively() {
            return getState() != 0;
        }
        // 最简单粗暴的锁资源,没有读写锁,可重入锁等等
        protected boolean tryAcquire(int unused) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        protected boolean tryRelease(int unused) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        public void lock()        { acquire(1); }
        public boolean tryLock()  { return tryAcquire(1); }
        public void unlock()      { release(1); }
        public boolean isLocked() { return isHeldExclusively(); }

        void interruptIfStarted() {
            Thread t;
            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
                try {
                    t.interrupt();
                } catch (SecurityException ignore) {
                }
            }
        }
    }

关键成员变量

// ctl变量保存了两个元素:workcount线程数量和runstate线程池运行状态
// runstate只有5中情况,3个字节可以表示完。int类型占32个字节,还剩29个字节,这29个字节表示workCount。
//组成就是:高3位表示runstate,低29位表示workcount
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    private static final int COUNT_BITS = Integer.SIZE - 3;
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

    // 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;
  // 堵塞队列
 private final BlockingQueue<Runnable> workQueue;
// 可重入锁,锁住一些并发操作,比如,添加工作线程
    private final ReentrantLock mainLock = new ReentrantLock();

    /**
     * Set containing all worker threads in pool. Accessed only when
     * holding mainLock.
     */
    private final HashSet<Worker> workers = new HashSet<Worker>();

    /**
     * Wait condition to support awaitTermination
     */
    private final Condition termination = mainLock.newCondition();

    /**
     * Tracks largest attained pool size. Accessed only under
     * mainLock.
     */
  // 最大线程数容量,实际最大开启过的线程数
    private int largestPoolSize;

    /**
     * Counter for completed tasks. Updated only on termination of
     * worker threads. Accessed only under mainLock.
     */
    private long completedTaskCount;

    /*
     * All user control parameters are declared as volatiles so that
     * ongoing actions are based on freshest values, but without need
     * for locking, since no internal invariants depend on them
     * changing synchronously with respect to other actions.
     */

    private volatile ThreadFactory threadFactory;

    /**
     * Handler called when saturated or shutdown in execute.
     */
    private volatile RejectedExecutionHandler handler;

    /**
     * Timeout in nanoseconds for idle threads waiting for work.
     * Threads use this timeout when there are more than corePoolSize
     * present or if allowCoreThreadTimeOut. Otherwise they wait
     * forever for new work.
     */
    private volatile long keepAliveTime;

    /**
     * If false (default), core threads stay alive even when idle.
     * If true, core threads use keepAliveTime to time out waiting
     * for work.
     */
    private volatile boolean allowCoreThreadTimeOut;
    // 核心线程数
    private volatile int corePoolSize;

    /**
     * Maximum pool size. Note that the actual maximum is internally
     * bounded by CAPACITY.
     */
    // 最大线程数
    private volatile int maximumPoolSize;

    /**
     * The default rejected execution handler
     */
    // 默认抛弃策略是报错
    private static final RejectedExecutionHandler defaultHandler =
        new AbortPolicy();

构造函数
初始化一些成员变量

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

关键方法
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();
        // 正在运行的工作线程数小于核心线程数,则addWorker方法开启新的工作线程
// 如果已开启的工作线程数大于或等于核心线程数,则把任务添加入堵塞队列
// 添加失败,则继续开启工作线程,如果已经开启线程数小于最大线程数,则添加成功,否则,使用指定的拒绝策略拒绝
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        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);
        }
        // 添加失败,则继续开启非核心线程执行任务
        else if (!addWorker(command, false))
            reject(command);
    }
 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);
                // core为true,则和核心线程数比较,core为false,则和最大线程数比较
                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
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            // 构建新workker工作线程,firstTask为传入的runnable,thread为根据传入的runnable构建的线程
            w = new Worker(firstTask);
            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());

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                // 添加成功,则启动新工作线程,新线程会执行worker类的run方法
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }
Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
             // 开启线程后,第一次执行的是本身的worker任务,而不是从队列中取任务。
            this.firstTask = firstTask;
            // worker的thread为根据传入的runnable构建的线程,故开启线程,则会运行run方法
            this.thread = getThreadFactory().newThread(this);
        }

启动工作线程之后

 /** Delegates main run loop to outer runWorker  */
        public void run() {
            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为空方法,用户可以重写它,在执行任务前,
                  // 可以执行一些用户自定义操作
                    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为空方法,用户可以重写它,在执行任务后,
                      // 可以执行一些用户自定义操作
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
             // 直到到这里,说明这个工作线程要死了。要不线程池非runtime状态,要不堵塞队列空了,做一些资源收尾操作
            processWorkerExit(w, completedAbruptly);
        }
    }
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 {
                 // 需要超时关闭,则堵塞队列为空,poll方法超时则返回不会一直堵塞,不需要超时关闭,则take方法会一直堵塞
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

再看一个方法getActiveCount方法,
不能用executorService.getActiveCount()方法查看线程数,因为,这个方法查看的并非是真正的线程数,而是正在执行任务的线程数,看源码就会发现,只会对没有unlock的work技术,而work只要执行完了task.run方法就会释放lock,也就不会计数。

public int getActiveCount() {
        final ReentrantLock mainLock = this.mainLock;
        mainLock.lock();
        try {
            int n = 0;
            for (Worker w : workers)
                if (w.isLocked())
                    ++n;
            return n;
        } finally {
            mainLock.unlock();
        }
    }

总结:ThreadPoolExecutor大概的运行流程是:指定核心线程数,最大线程数,堵塞队列类型,大小,抛弃策略,非核心线程空闲时间。execute提交任务的时候,如果已经开启的工作线程数小于核心线程数,则开启工作线程处理这个任务,并且会一直从堵塞队列取任务执行,堵塞队列为空,则堵塞这个线程。如果已经开启的工作线程数大于核心线程数,则将任务放入堵塞队列,直到堵塞队列放不下之后,开启非核心线程数执行任务,如果总线程数小于最大线程数,则开启成功,否则,开启失败,走指定的拒绝策略。非核心线程数,空闲指定时间后会关闭,就是当堵塞队列没有任务了一段时间后,非核心线程会关闭,核心线程会一直堵塞,不会关闭。

上一篇下一篇

猜你喜欢

热点阅读