如果ThreadPoolExecutor 的submit() 方法已饱和,如何使其阻塞? [英] How to make ThreadPoolExecutor's submit() method block if it is saturated?

查看:60
本文介绍了如果ThreadPoolExecutor 的submit() 方法已饱和,如何使其阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a ThreadPoolExecutor such that when it has reached its maximum size and the queue is full, the submit() method blocks when trying to add new tasks. Do I need to implement a custom RejectedExecutionHandler for that or is there an existing way to do this using a standard Java library?

推荐答案

我刚刚找到的可能解决方案之一:

One of the possible solutions I've just found:

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 的东西,因为它似乎是处理这种情况的标准方法.

Are there any other solutions? I'd prefer something based on RejectedExecutionHandler since it seems like a standard way to handle such situations.

这篇关于如果ThreadPoolExecutor 的submit() 方法已饱和,如何使其阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆