gpt4 book ai didi

java - 为什么 BoundedExecutor 必须捕获 RejectedExecutionException?

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:30 25 4
gpt4 key购买 nike

《Java并发实践》一书中的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()契约(Contract)的一部分是它可以抛出 RejectedExecutionException :

if this task cannot be accepted for execution

这对于任何给定的 Executor 实现意味着什么取决于该实现的判断。我可以创建一个 OnlyOnSundaysExecutor 来拒绝任务,除非一周中的当天是星期日。您必须检查各种 Executor 实现的文档,以了解它们在什么情况下会抛出 RejectedExecutionException 异常。

关于java - 为什么 BoundedExecutor 必须捕获 RejectedExecutionException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45288417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com