这是 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 块替换 catch 块不是更好吗?
这是我接受 Callable 而不是 Runnable 的 BoundedExecutor 的实现:
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;
}
}
}
这是一个正确的实现吗?
谢谢!