ThreadPoolExecutor和ArrayBlockingQueue组合不起作用

时间:2019-03-18 18:31:21

标签: spring spring-boot threadpoolexecutor

我正在使用spring的ThreadPoolExecutor。有人可以告诉我,当任务队列已满时,如何拒绝任务队列中的其他任务?基本上,我试图限制队列中的任务数量。即使当任务正在队列中运行时,队列也始终保持接受新任务。它不会抛出RejectedExecutionException

我正在使用以下代码在应用程序启动时创建ThreadPoolExecutor:

@SpringBootApplication
@EnableSwagger2
@EnableFeignClients
@EnableAsync
@EnableScheduling
public class MyApplication {

  public static void main(String[] args) throws Throwable {
    SpringApplication.run(TpsRegistrationApplication.class, args);
  }

  @Bean(name = "threadPoolExecutor")
  public ThreadPoolExecutor threadPoolExecutor() {
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(1, true);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.MILLISECONDS,
        blockingQueue, new RejectedExecutionHandler() {

          @Override
          public void rejectedExecution(Runnable r, java.util.concurrent.ThreadPoolExecutor executor) {
            // TODO Auto-generated method stub
            throw new TooManyRequestsException();
          }
        });
    // Let start all core threads initially
    executor.prestartAllCoreThreads();
    return executor;
  }

}

然后我正在使用threadPoolExecutor执行一个Runnable:

@Autowired
  private ThreadPoolExecutor threadPoolExecutor;

  @RequestMapping(value = "/test/executor", method = RequestMethod.POST)
  public @ResponseBody ResponseEntity<Void> testExecutor(@Valid @RequestBody String name) {
    threadPoolExecutor.execute(new RunnableTask(name));
    return new ResponseEntity<>(HttpStatus.OK);
  }

0 个答案:

没有答案