这里是来自Java并发实践的代码,展示了如何在工作队列已满时通过使用信号量
来限制任务注入(inject)率来使执行阻塞。信号量等于池大小加上您要允许的排队任务数。
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 {
semaphore.acquire();
try {
exec.execute(new Runnable() {
public void run() {
try {
command.run();
} finally {
semaphore.release();
}
}
});
} catch (RejectedExecutionException e) {
semaphore.release();
}
}
}
我的问题是关于
catch (RejectedExecutionException e) { semaphore.release(); }
上面有semaphore.acquire();
,这不是没有必要吗?
如果工作队列已满,则“semaphore.acquire”应该被阻止,并且不会出现 RejectedExecutionException
。
最佳答案
文档说如果无法接受执行此任务,则抛出 RejectedExecutionException
。您希望确保在由于任何原因无法接受任务时释放信号量。
关于java - 这段关于信号量的代码片段有必要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281712/