当前位置:   article > 正文

ThreadPoolExecutor(二)——execute_threadpoolutil.execute

threadpoolutil.execute

1.execute方法

  1. /**
  2. * Executes the given task sometime in the future. The task
  3. * may execute in a new thread or in an existing pooled thread.
  4. *
  5. * If the task cannot be submitted for execution, either because this
  6. * executor has been shutdown or because its capacity has been reached,
  7. * the task is handled by the current {@code RejectedExecutionHandler}.
  8. *
  9. * @param command the task to execute
  10. * @throws RejectedExecutionException at discretion of
  11. * {@code RejectedExecutionHandler}, if the task
  12. * cannot be accepted for execution
  13. * @throws NullPointerException if {@code command} is null
  14. */
  15. public void execute(Runnable command) {
  16. if (command == null)
  17. throw new NullPointerException();
  18. /*
  19. * Proceed in 3 steps:
  20. *
  21. * 1. If fewer than corePoolSize threads are running, try to
  22. * start a new thread with the given command as its first
  23. * task. The call to addWorker atomically checks runState and
  24. * workerCount, and so prevents false alarms that would add
  25. * threads when it shouldn't, by returning false.
  26. *
  27. * 2. If a task can be successfully queued, then we still need
  28. * to double-check whether we should have added a thread
  29. * (because existing ones died since last checking) or that
  30. * the pool shut down since entry into this method. So we
  31. * recheck state and if necessary roll back the enqueuing if
  32. * stopped, or start a new thread if there are none.
  33. *
  34. * 3. If we cannot queue task, then we try to add a new
  35. * thread. If it fails, we know we are shut down or saturated
  36. * and so reject the task.
  37. */
  38. int c = ctl.get();
  39. if (workerCountOf(c) < corePoolSize) {
  40. if (addWorker(command, true))
  41. return;
  42. c = ctl.get();
  43. }
  44. if (isRunning(c) && workQueue.offer(command)) {
  45. int recheck = ctl.get();
  46. if (! isRunning(recheck) && remove(command))
  47. reject(command);
  48. else if (workerCountOf(recheck) == 0)
  49. addWorker(null, false);
  50. }
  51. else if (!addWorker(command, false))
  52. reject(command);
  53. }
看方法注释:

执行给定的任务在将来的某个时间。该任务可能会用一个新的线程来执行,也有可能用线程池中一个已有的线程来执行。

如果该executor已经被shutdown了,或者因为容量已满,任务不会被执行,通过RejectedExecutionHandler来处理剩下流程。

将来的某个时间执行:说的是任务会入队列,然后根据线程池目前的各项指标状况来决定何时执行。

新的线程或已有线程:根据线程池的各项指标状况来决定是唤醒线程池中一个已有的阻塞线程来执行还是new一个Thread来执行任务。

2.execute方法的三个步骤

看方法内部注释:

1.如果当前正在run的线程数小于corePoolSize,那么就调用addWorker方法来new一个线程用来执行传入的任务。

对应代码片:

  1. int c = ctl.get();
  2. if (workerCountOf(c) < corePoolSize) {
  3. if (addWorker(command, true))
  4. return;
  5. c = ctl.get();
  6. }
2.如果addWorker方法执行失败了,任务要入队列,如果成功入队列了,需要做double check来处理一些极端情况,比如线程池是否shutdown了等等。

对应代码片:

  1. if (isRunning(c) && workQueue.offer(command)) {
  2. int recheck = ctl.get();
  3. if (! isRunning(recheck) && remove(command))
  4. reject(command);
  5. else if (workerCountOf(recheck) == 0)
  6. addWorker(null, false);
  7. }

3.如果任务无法入队列,再次尝试addWorker,这次是用正在run的线程数和maximumPoolSize比,如果超过了maximumPoolSize则reject任务,说明线程池已经饱和了。

对应代码片:

  1. else if (!addWorker(command, false))
  2. reject(command);

3.addWorker

  1. /*
  2. * Methods for creating, running and cleaning up after workers
  3. */
  4. /**
  5. * Checks if a new worker can be added with respect to current
  6. * pool state and the given bound (either core or maximum). If so,
  7. * the worker count is adjusted accordingly, and, if possible, a
  8. * new worker is created and started running firstTask as its
  9. * first task. This method returns false if the pool is stopped or
  10. * eligible to shut down. It also returns false if the thread
  11. * factory fails to create a thread when asked, which requires a
  12. * backout of workerCount, and a recheck for termination, in case
  13. * the existence of this worker was holding up termination.
  14. *
  15. * @param firstTask the task the new thread should run first (or
  16. * null if none). Workers are created with an initial first task
  17. * (in method execute()) to bypass queuing when there are fewer
  18. * than corePoolSize threads (in which case we always start one),
  19. * or when the queue is full (in which case we must bypass queue).
  20. * Initially idle threads are usually created via
  21. * prestartCoreThread or to replace other dying workers.
  22. *
  23. * @param core if true use corePoolSize as bound, else
  24. * maximumPoolSize. (A boolean indicator is used here rather than a
  25. * value to ensure reads of fresh values after checking other pool
  26. * state).
  27. * @return true if successful
  28. */
  29. private boolean addWorker(Runnable firstTask, boolean core) {
  30. retry:
  31. for (;;) {
  32. int c = ctl.get();
  33. int rs = runStateOf(c);
  34. // Check if queue empty only if necessary.
  35. if (rs >= SHUTDOWN &&
  36. ! (rs == SHUTDOWN &&
  37. firstTask == null &&
  38. ! workQueue.isEmpty()))
  39. return false;
  40. for (;;) {
  41. int wc = workerCountOf(c);
  42. if (wc >= CAPACITY ||
  43. wc >= (core ? corePoolSize : maximumPoolSize))
  44. return false;
  45. if (compareAndIncrementWorkerCount(c))
  46. break retry;
  47. c = ctl.get(); // Re-read ctl
  48. if (runStateOf(c) != rs)
  49. continue retry;
  50. // else CAS failed due to workerCount change; retry inner loop
  51. }
  52. }
  53. Worker w = new Worker(firstTask);
  54. Thread t = w.thread;
  55. final ReentrantLock mainLock = this.mainLock;
  56. mainLock.lock();
  57. try {
  58. // Recheck while holding lock.
  59. // Back out on ThreadFactory failure or if
  60. // shut down before lock acquired.
  61. int c = ctl.get();
  62. int rs = runStateOf(c);
  63. if (t == null ||
  64. (rs >= SHUTDOWN &&
  65. ! (rs == SHUTDOWN &&
  66. firstTask == null))) {
  67. decrementWorkerCount();
  68. tryTerminate();
  69. return false;
  70. }
  71. workers.add(w);
  72. int s = workers.size();
  73. if (s > largestPoolSize)
  74. largestPoolSize = s;
  75. } finally {
  76. mainLock.unlock();
  77. }
  78. t.start();
  79. // It is possible (but unlikely) for a thread to have been
  80. // added to workers, but not yet started, during transition to
  81. // STOP, which could result in a rare missed interrupt,
  82. // because Thread.interrupt is not guaranteed to have any effect
  83. // on a non-yet-started Thread (see Thread#interrupt).
  84. if (runStateOf(ctl.get()) == STOP && ! t.isInterrupted())
  85. t.interrupt();
  86. return true;
  87. }
先看注释:
检查根据当前线程池的状态是否允许添加一个新的Worker,如果可以,调整wc(workerCount,以后都用wc表示),代码块:
  1. if (compareAndIncrementWorkerCount(c))
  2. break retry;
如果线程被stop了或者可以shutdown,addWorker方法返回false。
如果thread工厂创建线程失败,需要a backout of workerCount( 这是个啥?!),代码块:
  1. // Recheck while holding lock.
  2. // Back out on ThreadFactory failure or if
  3. // shut down before lock acquired.
  4. int c = ctl.get();
  5. int rs = runStateOf(c);
  6. if (t == null ||
  7. (rs >= SHUTDOWN &&
  8. ! (rs == SHUTDOWN &&
  9. firstTask == null))) {
  10. decrementWorkerCount();
  11. tryTerminate();
  12. return false;
  13. }

3.1.addWorker局部分析(一)

  1. // Check if queue empty only if necessary.
  2. if (rs >= SHUTDOWN &&
  3. ! (rs == SHUTDOWN &&
  4. firstTask == null &&
  5. ! workQueue.isEmpty()))
  6. return false;
这个代码块的判断,如果是STOP,TIDYING和TERMINATED这三种状态,都会返回false。
如果是SHUTDOWN,还要判断firstTask和workQueue的状况,如果firstTask不是null,返回false。
如果firstTask是null,判断workQueue的状况,workQueue是空的时候,返回false。
这个还要再看看, SHUTDOWN状态下为什么要判断firstTask和队列,是要保证在SHUTDOWN的时候,新添加进来和队列中剩余的task要正常执行完吗

3.2.addWorker局部分析(二)

  1. for (;;) {
  2. int wc = workerCountOf(c);
  3. if (wc >= CAPACITY ||
  4. wc >= (core ? corePoolSize : maximumPoolSize))
  5. return false;
  6. if (compareAndIncrementWorkerCount(c))
  7. break retry;
  8. c = ctl.get(); // Re-read ctl
  9. if (runStateOf(c) != rs)
  10. continue retry;
  11. // else CAS failed due to workerCount change; retry inner loop
  12. }
这个代码块比上一个代码块更容易理解,是正常流程,当线程池没有处于RUNNING之外的几种状态的时候。
这时候的处理流程就是线程池是否创建线程的正常语义,依次进行下列比较:
1.和CAPACITY比较
如果当前wc超过CAPACITY(这个基本上不可能),返回false。
2.入参core为true,表示 addWorker的时候,wc还没到达corePoolSize,和corePoolSize比较
如果超过corePoolSize,返回false。否则原子操作compareAndIncrementWorkerCount修改wc值。
3.入参core为false,表示addWorker的时候队列已满,wc和maximumPoolSize比较
如果超过maximumPoolSize,返回false,否则原子操作compareAndIncrementWorkerCount修改wc值。

3.3.addWorker局部分析(三)

  1. final ReentrantLock mainLock = this.mainLock;
  2. mainLock.lock();
  3. try {
  4. // Recheck while holding lock.
  5. // Back out on ThreadFactory failure or if
  6. // shut down before lock acquired.
  7. int c = ctl.get();
  8. int rs = runStateOf(c);
  9. if (t == null ||
  10. (rs >= SHUTDOWN &&
  11. ! (rs == SHUTDOWN &&
  12. firstTask == null))) {
  13. decrementWorkerCount();
  14. tryTerminate();
  15. return false;
  16. }
  17. workers.add(w);
  18. int s = workers.size();
  19. if (s > largestPoolSize)
  20. largestPoolSize = s;
  21. } finally {
  22. mainLock.unlock();
  23. }
这个代码块,首先加锁,整个类用到这个锁的地方,除了获取该线程池的一些关键参数之外,就是shutdown和terminate等相关操作。
注释里说, Back out on ThreadFactory failure or if shut down before lock acquired,需要再看看。
如果这个if判断没有走,用该task构建的Worker就可以正常添加到workers这个HashSet中。

4.ctl

ctl是控制线程池状态的变量,由两部分组成,runState(高位)和workerCount(低28位),
private static int CAPACITY = (1 << COUNT_BITS) - 1;
CAPACITY是1左移COUNT_BITS,然后减一。
private static int COUNT_BITS = Integer.SIZE - 3;
COUNT_BITS是Integer的位数减去3,即29。
所以CAPACITY是100000000000000000000000000000-1=11111111111111111111111111111,表示低28位。这28位是表示运行的worker个数的。
private static final int RUNNING    = -1 << COUNT_BITS;
二进制,1111111111111111111111111111111111100000000000000000000000000000,和CAPACITY互补,所以~CAPACITY也是这个值。
private static final int STOP       =  1 << COUNT_BITS;
二进制,100000000000000000000000000000000
private static final int TIDYING    =  2 << COUNT_BITS;
二进制,1000000000000000000000000000000000
private static final int TERMINATED =  3 << COUNT_BITS;
二进制,1100000000000000000000000000000000
放在一起对比看,状态位置看标红三位:
11111111111111111111111111111 11111100000000000000000000000000000,RUNNING
00000000000000000000000000000 00000000000000000000000000000000000,SHUTDOWN
00000000000000000000000000000 00100000000000000000000000000000000,STOP
00000000000000000000000000000 01000000000000000000000000000000000,TIDYING
00000000000000000000000000000 01100000000000000000000000000000000,TERMINATED

5.和ctl相关的几组方法

private static int runStateOf(int c)     { return c & ~CAPACITY; }
把低28位都清掉了,只拿高位的运行状态。
private static int workerCountOf(int c)  { return c & CAPACITY; }
只取低28位,即拿workerCount。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/1008809
推荐阅读
相关标签
  

闽ICP备14008679号