这是《Java Concurrency in Practice》书中 BoundedExecutor 类的实现:
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();
}
}
}
是否有原因导致 RejectedExecutionException 被捕获而不是让它进一步传播?这样的话,如果任务被拒绝,那么提交任务的人就不会知道了。
用finally block 替换catch block 不是更好吗?
这是我的 BoundedExecutor 实现,它接受 Callable 而不是 Runnable:
public class BoundedExecutor {
private final ExecutorService exec;
private final Semaphore semaphore;
public BoundedExecutor(ExecutorService exec, int bound) {
this.exec = exec;
this.semaphore = new Semaphore(bound);
}
public <V> Future<V> submitTask(final Callable<V> command) throws InterruptedException {
semaphore.acquire();
try {
return exec.submit(new Callable<V>() {
@Override public V call() throws Exception {
try {
return command.call();
} finally {
semaphore.release();
}
}
});
} catch (RejectedExecutionException e) {
semaphore.release();
throw e;
}
}
}
这是一个正确的实现吗?
谢谢!
最佳答案
我发现将 catch 更改为 finally 的一个问题是,如果任务确实被提交并且没有抛出 RejectedExecutionException,您最终将释放信号量两次而不是一次。如果您想在 catch block 版本中传播异常,只需在释放信号量后添加 throw e;
即可。
关于Java并发实践: BoundedExecutor implementation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9374578/