tomcat优化jdk原生的线程池

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

tomcat优化jdk原生的线程池
•为啥要优化
1.1、由于tomcat 处理的都是一些网络方面的线程任务,都是IO类型的
2.2、JDK原生线程池,当核心线程满了之后往队列里面存放,这样不符合web容器的任务
3.3、tomcat修改为,核心线程满了之后,再创建非核心线程。

最后再往队列任务里面存放
•优化的手段
1.public void execute(Runnable command) {
2.if (command == null)
3.throw new NullPointerException();
4.
5.int c = ctl.get();
6.if (workerCountOf(c) < corePoolSize) {
7.if (addWorker(command, true))
8.return;
9.c = ctl.get();
10.}
11.if (isRunning(c) && workQueue.offer(command)) {
12.int recheck = ctl.get();
13.if (! isRunning(recheck) && remove(command))
14.reject(command);
15.else if (workerCountOf(recheck) == 0)
16.addWorker(null, false);
17.}
18.else if (!addWorker(command, false))
19.reject(command);
20.}
上述代码中 workQueue.offer(command) 这里的逻辑可以换成,非核心线程未满都返回false。

这样就可以创建非核心线程了队列进行定制为TaskQueue
•TaskQueue核心代码如下
1.@Override
2.public boolean offer(Runnable o) {
3.//we can't do any checks
4.if (parent==null) return super.offer(o);
5.//we are maxed out on threads, simply queue the object
6.if (parent.getPoolSize() == parent.getMaximumPoolSize()) return super.offer(o);
7.//we have idle threads, just add it to the queue
8.if (parent.getSubmittedCount()<(parent.getPoolSize())) return super.offer(o);
9.//if we have less threads than maximum force creation of
a new thread
10.if
(parent.getPoolSize()<parent.getMaximumPoolSize()) return false;
11.//if we reached here, we need to add it to the queue
12.return super.offer(o);
13.}
•tomcat的线程池对象也定制了一下,主要不同点为
1.public void execute(Runnable command, long timeout, TimeUnit unit) {
2.submittedCount.incrementAndGet();
3.try {
4.super.execute(command);
5.} catch (RejectedExecutionException rx) {
6.if (super.getQueue() instanceof TaskQueue) {
7.final TaskQueue queue = (TaskQueue)super.getQueue();
8.try {
9.if (!queue.force(command, timeout, unit)) {
10.submittedCount.decrementAndGet();
11.throw new RejectedExecutionException("Queue capacity is full.");
12.}
13.} catch (InterruptedException x) {
14.submittedCount.decrementAndGet();
15.throw new RejectedExecutionException(x);
16.}
17.} else {
18.submittedCount.decrementAndGet();
19.throw rx;
20.}
21.
22.}
23.}
24.
25.@Override
26.protected void afterExecute(Runnable r, Throwable t) {
27.submittedCount.decrementAndGet();
28.
29.if (t == null) {
30.stopCurrentThreadIfNeeded();
31.}
32.}
增加了重试功能,被拒绝之后,直接强制往队列里面放
备注:变量 submittedCount 是为了统计已经提交到线程池但还没有完成任务的数目这里变量会在TaskQueue offer方法里面使用,看是否存在空闲的线程。

相关文档
最新文档