Multithreading Spring@Async因rejectedExecutionexception失败

Multithreading Spring@Async因rejectedExecutionexception失败,multithreading,threadpoolexecutor,spring-async,Multithreading,Threadpoolexecutor,Spring Async,我们需要并行运行任务,所以我们使用spring@Async特性。为了提供executor配置,我们正在创建一个executor bean @Bean(name = "async") public Executor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSi

我们需要并行运行任务,所以我们使用spring@Async特性。为了提供executor配置,我们正在创建一个executor bean

@Bean(name = "async")
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(5);
        executor.setThreadNamePrefix("MyExecutor-");
        executor.initialize();
        return executor;
    } 
一旦并行任务的数量超过maxpoolSize+队列大小,下一个任务提交就会失败,并出现rejectedExecutionexception

为了克服这个问题,我们从源代码中研究了调用方中止策略:它提供了一种工具,在队列和线程已满的情况下,主线程本身可以运行任务

设置需要:executor.setRejectedExecutionHandler(新的ThreadPoolExecutor.CallerRunPolicy())

问题1。我需要了解ThreadPoolTaskExecutor使用LinkedBlocking队列,我的期望是,一旦最大池线程和队列大小已满并被占用,主线程将在提交新任务时被阻塞,但它会因RejectedException而失败,即使ThreadPoolTaskExecutor中存在阻塞队列


问题2。要克服这一问题,我们如何实现一种阻塞机制,使main在提交新任务时不会失败,也不会自行运行(如executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunPolicy())但是被阻塞,队列中的可用空间无法将任务放入队列?

无限期地阻塞主线程可能会导致死锁情况。这就是为什么要为应用程序用户提供一个处理程序,以决定当线程池队列容量超过时应该采取什么行为

正如下面的线程中所讨论的,可以实现所需阻塞行为的各种实现,但应该注意阻塞的时间和其他死锁场景