一尘不染

Java 如果ThreadPoolExecutor的submit()方法已饱和,如何使之阻塞?

java

我想创建一个ThreadPoolExecutor这样,当它达到最大大小并且队列已满时,该submit()方法将在尝试添加新任务时阻塞。我是否需要为此实现一个自定义RejectedExecutionHandler,或者是否存在使用标准Java库执行此操作的现有方法?


阅读 1383

收藏
2020-03-15

共1个答案

一尘不染

我刚刚发现的可能解决方案之一:

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因为这似乎是处理此类情况的标准方法。

2020-03-15