打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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. int c = ctl.get();
    5. if (workerCountOf(c) < corePoolSize) {
    6. if (addWorker(command, true))
    7. return;
    8. c = ctl.get();
    9. }
    10. if (isRunning(c) && workQueue.offer(command)) {
    11. int recheck = ctl.get();
    12. if (! isRunning(recheck) && remove(command))
    13. reject(command);
    14. else if (workerCountOf(recheck) == 0)
    15. addWorker(null, false);
    16. }
    17. else if (!addWorker(command, false))
    18. reject(command);
    19. }

    上述代码中  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. @Override
  24. protected void afterExecute(Runnable r, Throwable t) {
  25. submittedCount.decrementAndGet();
  26. if (t == null) {
  27. stopCurrentThreadIfNeeded();
  28. }
  29. }

增加了重试功能  ,被拒绝之后,直接强制往队列里面放

备注:变量 submittedCount  是为了统计已经提交到线程池但还没有完成任务的数目    这里变量会在TaskQueue offer方法里面使用,看是否存在空闲的线程

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
java多线程设计模式详解之三
「DUBBO系列」线程池策略详解
线程池任务队列
DeferredResult
用过C#写串口程序的请进! 中国电子开发网(www.ourdev.cn)
Windows消息机制要点
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服