jdk提供的线程池,当核心线程数已满,但是最大线程池数未满,来一个任务时,会先将任务加入阻塞队列。队列满之后才会创建线程来处理任务,这是比较适合cpu密集型任务的,但是像tomcat这种服务器程序就不太适合这种执行流程了。tomcat需要用户请求到达时马上就创建线程来处理,而不是加入阻塞队列。
先看看jdk原生线程池的执行流程。
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);
}
第二步中workQueue.offer(command)这一步是核心,tomcat也是通过改造这一步来实现核心线程数满时来任务直接创建线程的方式的。
public boolean offer(Runnable o) {
if (this.parent == null) {
return super.offer(o);
} else if (this.parent.getPoolSize() == this.parent.getMaximumPoolSize()) {
return super.offer(o);
} else if (this.parent.getSubmittedCount() <= this.parent.getPoolSize()) {
return super.offer(o);
} else {
return this.parent.getPoolSize() < this.parent.getMaximumPoolSize() ? false : super.offer(o);
}
}