Java并发实践: BoundedExecutor implementation

标签 java exception concurrency executor

这是《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/

相关文章:

java - 小服务程序 3.1 : how to handle body in DELETE request

java - 在静态主方法中的 While 内尝试/捕获

c# - 是否可以生成排除内部方法的 .NET 堆栈跟踪?

java - 并发运行 100,000 个进程

java - 使用 core-nlp 的 DocumentPreprocessor 拆分句子时处理连词

java - 对具有重试逻辑的方法进行单元测试

java - 自定义 Spring Boot 错误响应代码而不更改默认主体

异常跟踪解决方案

java - 同步块(synchronized block) : "expression expected"

java - CompletableFuture.allOf() 在等待完成时是否比使用 CompletableFuture.join() 的循环有任何优势?