至于《 Java Concurrency in Practice》一书中的BoundedExecutor,信号量限制了任务提交。基础执行程序何时会引发RejectedExecutionException?也许操作系统线程不足时?
public class BoundedExecutor {
private final Executor exec;
private final Semaphore semaphore;
public BoundedExecutor(Executor exec, int bound) {
this.exec = exec;
this.semaphore = new Semaphore(bound);
}
public void submitTask(final Runnable command) throws InterruptedException, RejectedExecutionException
{
semaphore.acquire();
try {
exec.execute(new Runnable() {
@Override public void run() {
try {
command.run();
} finally {
semaphore.release();
}
}
});
} catch (RejectedExecutionException e) {
semaphore.release();
throw e;
}
}
}
最佳答案
Executor.execute()
合同的一部分是它可以抛出RejectedExecutionException
:
如果无法接受此任务以执行
对于任何给定的Executor
实现,这意味着什么取决于该实现。我可以创建一个拒绝任务的OnlyOnSundaysExecutor
,除非当前的星期几是星期日。您必须查看各种Executor
实现的文档,以了解它们在什么情况下会引发RejectedExecutionException
异常。
关于java - 为什么BoundedExecutor必须捕获RejectedExecutionException?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45288417/