如何使ThreadPoolExecutor的submit()方法块如果它饱和? [英] How to make ThreadPoolExecutor's submit() method block if it is saturated?
问题描述
我想创建一个 ThreadPoolExecutor
,当它已达到其最大大小和队列已满, sumbit()
方法在尝试添加新任务时阻止。我需要实现一个自定义 RejectedExecutionHandler
,或者有一个现有的方法来使用标准的Java库?
I want to create a ThreadPoolExecutor
such that when it has reached its maximum size and the queue is full, the sumbit()
method blocks when trying to add new tasks. Do I need to implement a custom RejectedExecutionHandler
for that or is there an existing way to do this using standard java library?
推荐答案
我刚刚发现的一个可能的解决方案:
One of the possible solutions I've just found:
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() {
public void run() {
try {
command.run();
} finally {
semaphore.release();
}
}
});
} catch (RejectedExecutionException e) {
semaphore.release();
throw e;
}
}
}
我更喜欢基于 RejectedExecutionHandler
的东西,因为它似乎是处理这种情况的标准方式。
Are there any other solutions? I'd prefer something based on RejectedExecutionHandler
since it seems like a standard way to handle such situations.
这篇关于如何使ThreadPoolExecutor的submit()方法块如果它饱和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!