Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 675
Fixpoint Avatar asked Jan 04 '10 17:01

Fixpoint


People also ask

Does ExecutorService submit block?

a. executorService. submit() will start to block once all threads are busy and the internal queue is full.

What happens if you submit a task when the queue of the thread pool is already filled?

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.

Which method can be used to stop the Threadpool 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.

How do I stop all threads in ExecutorService?

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.


1 Answers

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.

like image 149
Fixpoint Avatar answered Sep 20 '22 13:09

Fixpoint