RejectedExecutionException空闲线程但满队列 [英] RejectedExecutionException free threads but full queue

查看:942
本文介绍了RejectedExecutionException空闲线程但满队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是导致这个RejectedExecutionException?

  [运行,池大小= 40,活动线程= 3,排队任务= 20 ,完成的任务= 180] 

ThreadPoolExecutor:



< ThreadPoolExecutor(30,40,10,TimeUnit.MINUTES,
new ArrayBlockingQueue&RunEvent

池大小为40,只有3个线程处于活动状态,为什么不使用其余的线程?

解决方案


RejectedExecutionException空闲线程但完全队列


这可能是一个竞争条件。在某些时候,你已经将超过60个任务添加到了池中。 40个线程正在运行,并将第二十一个任务添加到 ArrayBlockingQueue 中,并将其拒绝。但是,当您返回打印统计数据时,作业已经完成,因此目前只有3个正在运行的线程。



您可以添加一个 RejectedExecutionHandler 将阻止生产者的处理程序:

  threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() 
@Override
public void rejectedExecution(Runnable r,ThreadPoolExecutor executor){
try {
//这将阻止生产者,直到队列
执行器中有空格。 getQueue()。put(r);
} catch(InterruptedException e){
throw new RejectedExecutionException(
Unexpected InterruptedException,e);
}
}
});


What is causing this RejectedExecutionException?

[Running, pool size = 40, active threads = 3, queued tasks = 20, completed tasks = 180]

ThreadPoolExecutor:

new ThreadPoolExecutor(30, 40, 10, TimeUnit.MINUTES,
     new ArrayBlockingQueue<Runnable>(20), threadFactory);

Pool size is 40 and only 3 threads are active, so why it is not using rest of them?

解决方案

RejectedExecutionException free threads but full queue

This is probably a race condition. At some point you had added more than 60 tasks to the pool. 40 were running in threads and it went to add the 21st task to the ArrayBlockingQueue and it rejected it. However, when you go back to print out the stats, the jobs have finished so there are only 3 running threads at that moment.

You can add a RejectedExecutionHandler handler which will block the producer:

threadPool.setRejectedExecutionHandler(new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        try {
            // this will block the producer until there's room in the queue
            executor.getQueue().put(r);
        } catch (InterruptedException e) {
            throw new RejectedExecutionException(
                "Unexpected InterruptedException", e);
        }
    }
});

这篇关于RejectedExecutionException空闲线程但满队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆