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?
a. executorService. submit() will start to block once all threads are busy and the internal queue is full.
Remember: If corePoolSize or more threads are running, the executor prefers queuing the task than creating a new thread. If the queue is full and creating a new thread would exceed maximumPoolSize the submitted task is rejected by the executor.
When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing.
We'll first use the shutdown method of ExecutorService to terminate a thread pool gracefully. When we invoke shutDown, the thread pool stops accepting new tasks. Then, it waits for already submitted tasks to complete even if they didn't start yet.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With