Java ThreadPoolExecutor出现意外错误

Java ThreadPoolExecutor出现意外错误,java,exception,threadpoolexecutor,Java,Exception,Threadpoolexecutor,在下面放一个简单的测试程序,它应该并行执行一些任务。每次我们提交6项任务并等待完成。然后,提交另一组任务 import java.util.concurrent.*; public class ThreadExecutorTest { public static void main(String... args) { ThreadPoolExecutor ex = new ThreadPoolExecutor( 15, 20, 10, TimeU

在下面放一个简单的测试程序,它应该并行执行一些任务。每次我们提交6项任务并等待完成。然后,提交另一组任务

 import java.util.concurrent.*;

public class ThreadExecutorTest {

  public static void main(String... args) {
    ThreadPoolExecutor ex   = new ThreadPoolExecutor(   15, 20, 10,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(5));

    for (int i = 0; i< 200; i++) {
      submitTasks(ex);
    }
    System.out.println("Done");
  }

  private static void submitTasks(ThreadPoolExecutor ex) {
    Future f1 = ex.submit( new SampleTask());
    Future f2 = ex.submit( new SampleTask());
    Future f3 = ex.submit( new SampleTask());
    Future f4 = ex.submit( new SampleTask());
    Future f5 = ex.submit( new SampleTask());
    Future f6 = ex.submit( new SampleTask());

//    System.out.println("Max Pool Size " + ex.getMaximumPoolSize());
    System.out.println("Pool Size " + ex.getPoolSize());
//    System.out.println("Active count " + ex.getActiveCount());
//    System.out.println("Task Count " + ex.getTaskCount());
//    System.out.println("Queue length " + ex.getQueue().size());
//    System.out.println("Queue remainingCapacity " + ((ArrayBlockingQueue)ex.getQueue()).remainingCapacity());

    try {
      f1.get();
    } catch (ExecutionException eex) {
      System.out.println("ExecutionException reported later - " + eex.getMessage());
    }catch(Exception exp){
      System.out.println("Exception reported later - " + exp.getMessage());
    }
    try{
      f2.get();
    }catch(Exception exp){}
    try{
      f3.get();
    }catch(Exception exp){}
    try{
      f4.get();
    }catch(Exception exp){}
    try{
      f5.get();
    }catch(Exception exp){}
    try{
      f6.get();
    }catch(Exception exp){}

  }

  static class SampleTask implements Callable<Void> {
    @Override
    public Void call() throws Exception {
      try {
//        Thread.sleep(300);
      } catch (Exception e) {
        System.out.println("Exception reported");
      }
      return null;
    }
  }
}

ThreadPoolExecutor.execute
有一条注释,描述提交新任务时它的行为:

在您的情况下,当一次提交6个任务的批时,当池的当前大小小于核心大小时,这些提交会立即被分派到新的工作线程(请参见从0跳到6,以及从6跳到12)

一旦超过核心池大小但仍小于最大大小,任务将提交到队列,然后异步退出以在现有工作线程上运行,只要队列未满。由于这些任务都是背靠背提交的,所以很有可能在任何任务退出队列之前提交所有六个任务;因此,前五个线程将排队,剩下的一个将进入上述流程的步骤3:创建一个新的工作线程,并立即运行该任务。(这解释了后面从15跳到16,从16跳到17,依此类推。)


最终,这将导致线程池具有最大数量的工作线程,并且当达到上述流程的步骤3(如最后一段所述)时,执行者无法创建新的工作线程并拒绝任务。本质上,即使存在可用的工作线程,在过度填充队列之前,您也没有给执行者任何时间将任务从队列中拉出并在其上执行。

如果执行者有一个队列,则每个新任务都会首先放入队列中。如果您有像示例中那样的突发性执行,那么在任务出列和执行之前,队列会被填满。如果这些是现实的模式,您将需要一个更大的队列。请注意,在提交新任务之前,将调用Future get()以首先获取任务结果。在这种情况下,在提交下一批6个任务之前,Executor没有要处理的任务。但在提交6个任务之前,您不会调用它,因为您的队列中只能容纳5个任务。一旦线程池已满,如果无法将传入任务放入队列中,它将被拒绝(即使所有工作线程都处于空闲状态!)。
Pool Size 6
Pool Size 12
Pool Size 15
Pool Size 16
Pool Size 17
Pool Size 18
Pool Size 19
Pool Size 20
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@2328c243 rejected from java.util.concurrent.ThreadPoolExecutor@bebdb06[Running, pool size = 20, active threads = 0, queued tasks = 0, completed tasks = 53]
    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
    /*
     * 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.
     */