ThreadPoolExecutor源碼分析(待更新)

  • 線程池狀態

	//高3位用於表示狀態,低29位表示線程的數量
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    //29
    private static final int COUNT_BITS = Integer.SIZE - 3;
    //低29位全爲1,高3位爲0
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

    // 高3位爲111,低29爲0
    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 static int runStateOf(int c)     { return c & ~CAPACITY; }
    //清空高位,獲取線程數量
    private static int workerCountOf(int c)  { return c & CAPACITY; }
    private static int ctlOf(int rs, int wc) { return rs | wc; }
  • execute方法

	//重點分析
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        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);
    }
  • addWorker方法

private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);
            //狀態>=SHUTDOWN直接返回,
            // 除了(rs == SHUTDOWN && firstTask == null && !workQueue.isEmpty())
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
                //線程數量大於最大值,或者>=core ? corePoolSize : maximumPoolSize
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  
                //狀態改變的話就重試
                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 {
            w = new 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()) 
                            throw new IllegalThreadStateException();
                        workers.add(w);
                        int s = workers.size();
                        //這裏表示不理解,largestPoolSize居然會改變
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }
  • Worker類

	//Worker作爲Runnable,傳入自己的線程的構造函數中
	Worker(Runnable firstTask) {
    	setState(-1); // inhibit interrupts until runWorker
        this.firstTask = firstTask;
         //直接將this傳入,是不是不太妥
        this.thread = getThreadFactory().newThread(this);
    }
	//方法調用鏈thread.run() -> worker.run() -> runWorker()
	public void run() {
    	runWorker(this);
    }
    final void runWorker(Worker w){
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        //釋放鎖,允許讓其他線程中斷
        w.unlock();
        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; // 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);

            // 線程數量>核心線程數 並且設置了允許核心線程數超時
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
            
            //超時或者線程數量大於 maximumPoolSize
            if ((wc > maximumPoolSize || (timed && timedOut))
                    //隊列爲空
                && (wc > 1 || workQueue.isEmpty())) {
                //超時直接返回null.
                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;
            }
        }
    }



  • submit方法

	
	public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        //封裝成一個FutureTask(也是一個Runable)
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

	public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
	//將返回值注入,
	//outcome介紹: non-volatile, protected by state reads/writes
	protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章