Java併發編程之ThreadPoolExecutor線程池源碼剖析

  我們開始從 ThreadPoolExecutor 可以做什麼來說起,然後進行源碼剖析。
  ThreadPoolExecutor 的初始化方法爲:

    public ThreadPoolExecutorLocal(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) { . . . }


  1、第一個參數爲corePoolSize:即線程池的核心數量,比如是 10 ,那麼當線程生成了1個線程時,則會保留這個線程。因爲未超過10個,所以最多保留10個核心線程
  2、maximumPoolSize:最大線程數,即當核心線程都在運行,且 workQueue 已滿,則會增加臨時線程來執行任務,核心線程+臨時線程最大爲 maximumPoolSize。
  3、keepAliveTime,unit:臨時線程的保留時間,比如10s,則超過10s,臨時線程就會被銷燬(其實就是執行完畢,自動結束)
  4、workQueue:runnable存放的queue,線程會從此 queue 中來取runnable來執行。
  5、threadFactory:即創建線程的 Factory ,此會傳入一個runnable,然後讓你返回一個Thread,其實就是讓你調用Thread的
Thread(Runnable  runnable, String threadName)
即讓你給thread來起一個名字
  6、handler:拒絕執行的handler,當現在線程處於最大線程數,且queue也滿了的時候,則線程池則會拒絕執行,此時會回調這個方法,告訴你runnable被拒絕執行了。

  eg:

        ThreadPoolExecutorLocal threadPoolExecutorLocal = new ThreadPoolExecutorLocal(
                10,
                25,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(20),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "threadPoolExecutorLocal-Thread");
                    }
                },
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println(" runnable 被拒絕執行了" );
                    }
                });

此線程池核心線程爲 10 個,最大爲25個,超過的線程最多保留10s,queue的大小爲20個,創建的Thread的名稱固定爲 threadPoolExecutorLocal-Thread ,並且也實現了 RejectedExecutionHandler 。

 

一、關於線程池的一些問題:
  在分析源碼之前,我們先上幾個問題:
1、ThreadPoolExecutor初始就生成全部 core 的線程麼
2、ThreadPoolExecutor是如何指派線程來執行的?是讓指定線程wait,然後有 runnable 之後 notify 麼
3、如何從 Queue 中來取?當發現沒有可執行的core的時候放到 Queue 中,然後 core 在執行的的時候先從 core 的隊列中取?沒有就從 Queue 中來取?
4、如果超過了 Queue 的大小,是如何生成一個線程的?又如何保證這個線程在指定時候內不執行就刪除?    
    
 

二、線程池源碼剖析:

   1、ThreadPoolExecutor執行runnable的源碼:

    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();

        int c = ctl.get();
        // 當 當前執行線程小於核心線程的時候,執行addWorker(command, true),添加一個執行線程
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        // 如果不小於,那麼添加到 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);
        }
        // 如果 workQueue 添加不進去(一般情況即queue滿了),那麼執行addWorker(command, false),即添加一個執行線程
        else if (!addWorker(command, false))
            reject(command);
    }

  2、添加執行線程addWorker()的源碼:

    private boolean addWorker(Runnable firstTask, boolean core) {

        log.info(" 開始addWorker core爲" + core);

        retry:
        for (;;) {
            int c = ctl.get();

            int rs = runStateOf(c);

            if (rs >= SHUTDOWN &&
                    ! (rs == SHUTDOWN &&
                            firstTask == null &&
                            ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
               // core只有在這裏面使用了,只去判斷是否超過了core的大小或者max的大小,可以看到核心線程與臨時線程其實並沒有區別
                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;
        ThreadPoolExecutorLocal.Worker w = null;
        try {
            // 生成一個Worker
            w = new ThreadPoolExecutorLocal.Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                mainLock.lock();
                try {
                    
                    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();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

 即內部的做法爲:

   1、判斷是否可以添加線程。
    可以看到,先去使用 core 來判斷是否是核心線程或是臨時線程,不過這個 core 只是用來判斷數量的大小,爲true則判斷核心線程的數量,爲false則判斷最大線程數量。
  注意這個使用 for(;;)循環 與 compareAndIncrementWorkerCount 來避免併發問題,因爲同一時間只有一個線程能執行通過。
   2、判斷通過後添加worker:
    w = new ThreadPoolExecutorLocal.Worker(firstTask);
    判斷通過後,通過runnable來添加一個worker,我們看一下worker的方法:

    private final class Worker
            extends AbstractQueuedSynchronizer
            implements Runnable
    {

        private static final long serialVersionUID = 6138294804551838833L;

        Runnable firstTask;

        volatile long completedTasks;


        // 此爲初始構造方法
        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

        
        // run方法其實是去調用 ThreadPoolExecutor的 runWorker() 方法
        public void run() {
            runWorker(this);
        }


        protected boolean isHeldExclusively() {
            return getState() != 0;
        }
        
        // 由於繼承了AbstractQueuedSynchronizer,其實Worker是一個鎖,tryAcquire 與 tryRelease 方法,tryAcquire將狀態由0設置爲1,tryRelease將狀態設置爲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;
        }

......
}

  可以看到,Worker 裏面將runnable設置爲自己的task,然後生成一個thread,並將這個thread的runnable置爲自己。雖然真正的run方法是調用 ThreadPoolExecuto r的 runWorker() 方法,我認爲其實這是一個代理模式,也就是說 Worker 也實現了runnable,這是因爲我要對真正的runnable執行前,執行後做一些操作,所以我也實現了這個接口,以便對原先的runnable來做擴展。
  在 addWorker() 方法中,生成一個 Worker 後,得到其thread,然後調用其 start() 方法,裏面然後調用 Worker 的run() 方法,然後調用 ThreadPoolExecuto r的 runWorker() 方法。

 

下面主要看一下 runWorker() 方法與 getTask() 方法:

    final void runWorker(ThreadPoolExecutorLocal.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 ((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);
        }
    }

    private Runnable getTask() {
        boolean timedOut = false; 

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

            if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
                decrementWorkerCount();
                return null;
            }

            int wc = workerCountOf(c);

            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

            if ((wc > maximumPoolSize || (timed && timedOut))
                    && (wc > 1 || workQueue.isEmpty())) {
                // 如果超時沒有獲取到線程,那麼會在這裏面通過 compareAndDecrementWorkerCount 
                // 原子方法來減少count,只有減少了,才說明通過了原子方法,可以說明這個線程確確實實可以減少 
                // ,通過這個方法保證了core的穩定性。
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }

            try {

                //  在獲取task begin , 注意此線程會阻塞在 workQueue 的take()
                Runnable r = timed ?
                        workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                        workQueue.take();

                if (r != null) {
                    return r;
                }

                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

  可以看到,runWorker() 方法會得到Worker裏面的runnable,如果沒有沒有得到,則調用 getTask() 方法,我們剛開始生成一個核心線程,其Worker裏面是有runnable的,如果當其執行完了,會阻塞在 getTask() 中  workQueue.take() 方法中來得到一個 runnable 。
  所以核心方法看完了,我們繼續之前的 execute(Runnable) 方法,如果此時線程數量小於 core ,則生成一個worker來執行,worker會生成一個Thread,來代理執行任務,如果大於,則將 runnable 放置到queue中。如果queue中也滿了,那麼生成一個 addWorker(Runnable, false),注意這時候就判斷是否當前數量大於最大數量了,如果沒有,就生成一個,如果大於了,那麼就返回false,即執行不了。
  

三、問題回答

源碼剖析完畢,我們來解答一下之前的問題  

 1、ThreadPoolExecutor初始就生成 core 的線程麼?
  不是,通過源碼可以看到,是初始執行execute的時候纔會生成core線程。


 2、ThreadPoolExecutor是如何指派線程來執行的?是讓指定線程wait,然後有 runnable 之後 notify 麼
  不全是,初始執行的話裏面有runnable,再次獲取task的時候回阻塞在queue的take()方法中,其實也就是相當於 wait 與 notify 方法。

 3、如何從 Queue 中來取?當發現沒有可執行的core的時候放到 Queue 中,然後 core 在執行的的時候先從 core 的隊列中取?沒有就從 Queue 中來取?
  不是,注意其實並沒有分core的線程或者臨時的線程,都是線程,就是看誰最後能先超時退出,也就是誰先獲取到 getTask() 中的    compareAndDecrementWorkerCount(c) 方法,如果成功,則先退出,所以剛開始生成的core線程是很可能退出的。


4、如果超過了 Queue 的大小,是如何生成一個線程的?又如何保證這個線程在指定時候內不執行就刪除?    
    線程在超過了core的大小之後,會再次調用addWorker()方法,生成一個worker(只要不超過max的大小)。
         在得到task的時候,即 getTask() 方法,發現大小已經超過了core,那麼不會使用task的 take() 方法,即不管多長時間也等待的獲取,如果此時超過了core,就是調用poll(keepAliveTime) 方法,即在指定時間內獲取task,如果獲取不到,則返回再進行 getTask() 方法,此時 timed && timedOut 都爲true,那麼如果調用
               if (compareAndDecrementWorkerCount(c))
                    return null;
       成功了,就會退出。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章