Tomcat如何使用線程池處理遠程併發請求

Tomcat如何使用線程池處理遠程併發請求

經過了解學習tomcat如何處理併發請求,瞭解到線程池,鎖,隊列,unsafe類,下面的主要代碼來自java

java-jre:
sun.misc.Unsafe
java.util.concurrent.ThreadPoolExecutor
java.util.concurrent.ThreadPoolExecutor.Worker
java.util.concurrent.locks.AbstractQueuedSynchronizer
java.util.concurrent.locks.AbstractQueuedLongSynchronizer
java.util.concurrent.LinkedBlockingQueuenode

tomcat:
org.apache.tomcat.util.net.NioEndpoint
org.apache.tomcat.util.threads.ThreadPoolExecutor
org.apache.tomcat.util.threads.TaskThreadFactory
org.apache.tomcat.util.threads.TaskQueueapache

ThreadPoolExecutor

是一個線程池實現類,管理線程,減小線程開銷,能夠用來提升任務執行效率,tomcat

構造方法中的參數有併發

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

corePoolSize 是核心線程數
maximumPoolSize 是最大線程數
keepAliveTime 非核心線程最大空閒時間(超過期間終止)
unit 時間單位
workQueue 隊列,當任務過多時,先存放在隊列
threadFactory 線程工廠,建立線程的工廠
handler 決絕策略,當任務數過多,隊列不能再存聽任務時,該如何處理,由此對象去處理。這是個接口,你能夠自定義處理方式高併發

ThreadPoolExecutor在Tomcat中http請求的應用

此線程池是tomcat用來在接收到遠程請求後,將每次請求單獨做爲一個任務去處理,每次調用execute(Runnable)oop

初始化

org.apache.tomcat.util.net.NioEndpoint學習

NioEndpoint初始化的時候,建立了線程池this

public void createExecutor() {
        internalExecutor = true;
        TaskQueue taskqueue = new TaskQueue();
        //TaskQueue無界隊列,能夠一直添加,所以handler 等同於無效
        TaskThreadFactory tf = new TaskThreadFactory(getName() + "-exec-", daemon, getThreadPriority());
        executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), 60, TimeUnit.SECONDS,taskqueue, tf);
        taskqueue.setParent( (ThreadPoolExecutor) executor);
    }

在線程池建立時,調用prestartAllCoreThreads(), 初始化核心工做線程worker,並啓動.net

public int prestartAllCoreThreads() {
        int n = 0;
        while (addWorker(null, true))
            ++n;
        return n;
    }

當addWorker 數量等於corePoolSize時,addWorker(null,ture)會返回false,中止worker工做線程的建立

提交任務到隊列

每次客戶端過來請求(http),就會提交一次處理任務,

worker 從隊列中獲取任務運行,下面是任務放入隊列的邏輯代碼

ThreadPoolExecutor.execute(Runnable) 提交任務:

public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
       
        int c = ctl.get();
    	// worker數 是否小於 核心線程數   tomcat中初始化後,通常不知足第一個條件,不會addWorker
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
    	// workQueue.offer(command),將任務添加到隊列,
        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);
    }

workQueue.offer(command) 完成了任務的提交(在tomcat處理遠程http請求時)。

workQueue.offer

TaskQueue 是 BlockingQueue 具體實現類,workQueue.offer(command)實際代碼:

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    final AtomicInteger count = this.count;
    if (count.get() == capacity)
        return false;
    int c = -1;
    Node<E> node = new Node<E>(e);
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        if (count.get() < capacity) {
            enqueue(node); //此處將任務添加到隊列
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        }
    } finally {
        putLock.unlock();
    }
    if (c == 0)
        signalNotEmpty();
    return c >= 0;
}

// 添加任務到隊列
/**
     * Links node at end of queue.
     *
     * @param node the node
     */
private void enqueue(Node<E> node) {
    // assert putLock.isHeldByCurrentThread();
    // assert last.next == null;
    last = last.next = node; //鏈表結構 last.next = node; last = node
}

以後是worker的工做,worker在run方法中經過去getTask()獲取此處提交的任務,並執行完成任務。

線程池如何處理新提交的任務

添加worker以後,提交任務,由於worker數量達到corePoolSize,任務都會將放入隊列,而worker的run方法則是循環獲取隊列中的任務(不爲空時),

worker run方法:

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

循環獲取隊列中的任務

runWorker(worker)方法 循環部分代碼:

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(); // 上鎖
                try {
                    // 運行前處理
                    beforeExecute(wt, task);
                    // 隊列中的任務開始執行
                    task.run();
                    // 運行後處理
                    afterExecute(task, thrown);
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock(); // 釋放鎖
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

task.run()執行任務

鎖運用

ThreadPoolExecutor 使用鎖主要保證兩件事情,
1.給隊列添加任務,保證其餘線程不能操做隊列
2.獲取隊列的任務,保證其餘線程不能同時操做隊列

給隊列添加任務上鎖

public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        if (count.get() == capacity)
            return false;
        int c = -1;
        Node<E> node = new Node<E>(e);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();  //上鎖
        try {
            if (count.get() < capacity) {
                enqueue(node);
                c = count.getAndIncrement();
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();  //釋放鎖
        }
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }

獲取隊列任務上鎖

private Runnable getTask() {
        boolean timedOut = false; // Did the last poll() time out?
		// ...省略
        for (;;) {
            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take(); //獲取隊列中一個任務
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }
public E take() throws InterruptedException {
        E x;
        int c = -1;
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly(); // 上鎖
        try {
            while (count.get() == 0) {
                notEmpty.await(); //若是隊列中沒有任務,等待
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock(); // 釋放鎖
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }

volatile

在併發場景這個關鍵字修飾成員變量很常見,

主要目的公共變量在被某一個線程修改時,對其餘線程可見(實時)

sun.misc.Unsafe 高併發相關類

線程池使用中,有平凡用到Unsafe類,這個類在高併發中,能作一些原子CAS操做,鎖線程,釋放線程等。

sun.misc.Unsafe 類是底層類,openjdk源碼中有

原子操做數據

java.util.concurrent.locks.AbstractQueuedSynchronizer 類中就有保證原子操做的代碼

protected final boolean compareAndSetState(int expect, int update) {
        // See below for intrinsics setup to support this
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

對應Unsafe類的代碼:

//對應的java底層,實際是native方法,對應C++代碼
/**
* Atomically update Java variable to <tt>x</tt> if it is currently
* holding <tt>expected</tt>.
* @return <tt>true</tt> if successful
*/
public final native boolean compareAndSwapInt(Object o, long offset,
                                              int expected,
                                              int x);

方法的做用簡單來講就是 更新一個值,保證原子性操做
當你要操做一個對象o的一個成員變量offset時,修改o.offset,
高併發下爲保證準確性,你在操做o.offset的時候,讀應該是正確的值,而且中間不能被別的線程修改來保證高併發的環境數據操做有效。

即 expected 指望值與內存中的值比較是同樣的expected == 內存中的值 ,則更新值爲 x,返回true表明修改爲功

不然,指望值與內存值不一樣,說明值被其餘線程修改過,不能更新值爲x,並返回false,告訴操做者這次原子性修改失敗。

阻塞和喚醒線程

public native void park(boolean isAbsolute, long time); //阻塞當前線程

線程池的worker角色循環獲取隊列任務,若是隊列中沒有任務,worker.run 仍是在等待的,不會退出線程,代碼中用了notEmpty.await() 中斷此worker線程,放入一個等待線程隊列(區別去任務隊列);當有新任務須要時,再notEmpty.signal()喚醒此線程

底層分別是
unsafe.park() 阻塞當前線程
public native void park(boolean isAbsolute, long time);

unsafe.unpark() 喚醒線程
public native void unpark(Object thread);

這個操做是對應的,阻塞時,先將thread放入隊列,喚醒時,從隊列拿出被阻塞的線程,unsafe.unpark(thread)喚醒指定線程。

java.util.concurrent.locks.AbstractQueuedLongSynchronizer.ConditionObject 類中

經過鏈表存放線程信息

// 添加一個阻塞線程
private Node addConditionWaiter() {
            Node t = lastWaiter;
            // If lastWaiter is cancelled, clean out.
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node; //將新阻塞的線程放到鏈表尾部
            return node;
        }

// 拿出一個被阻塞的線程
 public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter; //鏈表中第一個阻塞的線程
            if (first != null)
                doSignal(first);
        }

// 拿到後,喚醒此線程
final boolean transferForSignal(Node node) {
            LockSupport.unpark(node.thread);
        return true;
    }
public static void unpark(Thread thread) {
        if (thread != null)
            UNSAFE.unpark(thread);
    }
相關文章
相關標籤/搜索