Это реализация класса BoundedExecutor в Java Параллелизм в практике книге:Java Параллелизм на практике: реализация 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?
Это моя реализация 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;
}
}
}
ли это правильное применение?
Спасибо!
Правильно! Я скорректировал мою версию BoundedExecutor выше. Работает ли он правильно? –