Fixpoint Fixpoint - 1 year ago 104
Java Question

How to make ThreadPoolExecutor's submit() method block if it is saturated?

I want to create a

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

Answer Source

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 {
        try {
            exec.execute(new Runnable() {
                public void run() {
                    try {
                    } finally {
        } catch (RejectedExecutionException e) {
            throw e;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download