tomcat线程池源码

目录

前言

一、ThreadPoolExecutor

二、TaskQueue

总结


前言

       jdk的原生线程池会尽量保证核心线程数的线程运行,但对于io密集型任务,应尽量使用更多的线程,tomcat对线程池进行了扩展,本文主要针对tomcat线程池源码中的重点内容进行分析。


一、ThreadPoolExecutor

        在tomcat的ThreadPoolExecutor中,对execute方法进行了重写,在当前任务被线程池拒绝时,会再次尝试将任务加入到等待队列中,尽可能保证任务能够被执行。

    public void execute(Runnable command, long timeout, TimeUnit unit) {
        //提交的任务数加一
        submittedCount.incrementAndGet();
        try {
            //调用juc线程池的execute
            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(sm.getString("threadPoolExecutor.queueFull"));
                    }
                } catch (InterruptedException x) {
                    submittedCount.decrementAndGet();
                    throw new RejectedExecutionException(x);
                }
            } else {
                submittedCount.decrementAndGet();
                throw rx;
            }

        }
    }

二、TaskQueue

        tomcat中的taskQueue继承了LinkedBlockingQueue,为了线程池而设计,修改了offer方法,并且记录了当前提交到线程池中的任务数,在任务加入到队列的时候进行判断。在当前线程数小于最大线程数的时候,不会加入到队列中,返回false,从而会新建线程执行,尽可能创建多的线程执行任务。

    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);
        //if we have less threads than maximum force creation of a new thread
        // 如果当前的线程数小于最大线程数,返回false,线程池会创建新线程处理
        if (parent.getPoolSize()<parent.getMaximumPoolSize()) return false;
        //if we reached here, we need to add it to the queue
        //当前线程数大于最大线程数。。。。。
        return super.offer(o);
    }


总结

         本文主要对tomcat中线程池的扩展进行了分析,内容比较多,没有全部覆盖,欢迎一块交流。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值