寫在前面java
本文是以同tomcat 7.0.57。 jdk版本1.7.0_80爲例。apache
線程池在tomcat中的建立實現爲:tomcat
public abstract class AbstractEndpoint<S> { public void createExecutor() { internalExecutor = true; TaskQueue taskqueue = new TaskQueue(); TaskThreadFactory tf = new TaskThreadFactory(getName() + "-exec-", daemon, getThreadPriority()); executor = new ThreadPoolExecutor(getMinSpareThreads(), getMaxThreads(), 60, TimeUnit.SECONDS,taskqueue, tf); taskqueue.setParent( (ThreadPoolExecutor) executor); } }
同時(重點):tomcat的線程池擴展了jdk的executor,並且隊列用的是本身的task queue,所以其策略與jdk的有所不一樣,須要注意一下。ide
tomcat線程池策略ui
場景1:接受一個請求,此時tomcat啓動的線程數尚未達到corePoolSize(tomcat裏頭叫minSpareThreads),tomcat會啓動一個線程來處理該請求;this
場景2:接受一個請求,此時tomcat啓動的線程數已經達到了corePoolSize,tomcat把該請求放入隊列(offer
),若是放入隊列成功,則返回,放入隊列不成功,則嘗試增長工做線程,在當前線程個數<maxThreads的時候,能夠繼續增長線程來處理,超過maxThreads的時候,則繼續往等待隊列裏頭放,等待隊列放不進去,則拋出RejectedExecutionException;atom
值得注意的是,使用LinkedBlockingQueue的話,默認是使用Integer.MAX_VALUE,即無界隊列(這種狀況下若是沒有配置隊列的capacity的話,隊列始終不會滿,那麼始終沒法進入開啓新線程到達maxThreads個數的地步,則此時配置maxThreads實際上是沒有意義的)。spa
而TaskQueue的隊列capacity爲maxQueueSize,默認也是Integer.MAX_VALUE。可是,其重寫offer方法,當其線程池大小小於maximumPoolSize的時候,返回false,即在必定程度改寫了隊列滿的邏輯,修復了使用LinkedBlockingQueue默認的capacity爲Integer.MAX_VALUE的時候,maxThreads失效的"bug"。從而能夠繼續增加線程到maxThreads,超過以後,繼續放入隊列。線程
tomcat的線程池使用了本身擴展的taskQueue,而不是Executors工廠方法裏頭用的LinkedBlockingQueue。(主要是修改了offer的邏輯
)TaskQueue實現的offer操做以下:code
package org.apache.tomcat.util.threads; import java.util.Collection; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; public class TaskQueue extends LinkedBlockingQueue<Runnable> {
private ThreadPoolExecutor parent = null; @Override public boolean offer(Runnable o) { //we can't do any checks if (parent==null) return super.offer(o); //we are maxed out on threads, simply queue the object if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o); //we have idle threads, just add it to the queue if (parent.getSubmittedCount()<(parent.getPoolSize())) return super.offer(o); //當其線程池大小小於maximumPoolSize的時候,返回false if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false; //if we reached here, we need to add it to the queue return super.offer(o); } }
ThreadPoolExecutor的提交方法
這裏改寫了jdk線程池默認的Rejected規則,即catch住了RejectedExecutionException。正常jdk的規則是core線程數+臨時線程數 >maxSize的時候,就拋出RejectedExecutionException。這裏catch住的話,繼續往taskQueue裏頭放
package org.apache.tomcat.util.threads; import java.util.concurrent.BlockingQueue; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.tomcat.util.res.StringManager; public class ThreadPoolExecutor extends java.util.concurrent.ThreadPoolExecutor { /** * {@inheritDoc} */ @Override public void execute(Runnable command) { execute(command,0,TimeUnit.MILLISECONDS); } public void execute(Runnable command, long timeout, TimeUnit unit) { submittedCount.incrementAndGet(); try { super.execute(command); } catch (RejectedExecutionException rx) { if (super.getQueue() instanceof TaskQueue) { final TaskQueue queue = (TaskQueue)super.getQueue(); try { if (!queue.force(command, timeout, unit)) { submittedCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full."); } } catch (InterruptedException x) { submittedCount.decrementAndGet(); Thread.interrupted(); throw new RejectedExecutionException(x); } } else { submittedCount.decrementAndGet(); throw rx; } } } }
重點看下queue.force 方法
public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException { if ( parent.isShutdown() ) throw new RejectedExecutionException("Executor not running, can't force a command into the queue"); return super.offer(o,timeout,unit); //forces the item onto the queue, to be used if the task is rejected }
注意的是這裏調用的super.offer(o,timeout,unit),即LinkedBlockingQueue,只有當列滿的時候,返回false,纔會拋出從新拋出RejectedExecutionException。
這裏改變了jdk的ThreadPoolExecutor的RejectedExecutionException拋出的邏輯,也就是超出了maxThreads不會拋出RejectedExecutionException,而是繼續往隊列丟任務,而taskQueue自己是無界的,所以能夠默認幾乎不會拋出RejectedExecutionException
回顧JDK線程池策略
public class ThreadPoolExecutor extends AbstractExecutorService { 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(); 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); } }
總結:
tomcat的線程池與jdk的使用無界LinkedBlockingQueue主要有以下兩點區別: