Fixpoint Fixpoint - 3 months ago 22
Java Question

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

I want to create a

ThreadPoolExecutor
such that when it has reached its maximum size and the queue is full, the
sumbit()
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 standard java library?

Answer

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;
        }
    }
}

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