Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle RejectedExecutionException with ThreadPoolExecutor in java

What is the best way to handle RejectedExecutionException while using a ThreadPoolExecutor in Java?

I want to ensure that the task submitted should not be overlooked and should surely get executed. As of now there are no hard real time requirements to get the task done.

One of the things I thought could be done was waiting in a loop till I know that there is space in the runnable queue, and then go on and add it to the queue.

Would be glad if people can share their experiences.

Adding the possible solution I though of:

while(executor.getQueue().remainingCapacity <= 0){
// keep looping
Thread.sleep(100);
};
//if the loop exits ,indicates that we have space in the queue hence 
//go ahead and add to the queue 
executor.execute(new ThreadInstance(params));
like image 453
Neeraj Avatar asked Feb 23 '12 12:02

Neeraj


People also ask

How do you prevent ThreadPoolExecutor?

You can call the cancel() function on the Future object to cancel the task before it has started running. If your task has already started running, then calling cancel() will have no effect and you must wait for the task to complete.

Is ThreadPoolExecutor thread safe Java?

These types of contracts are outside of the scope of a Java interface. However, ThreadPoolExecutor both is and is clearly documented as being thread-safe.

How does ThreadPoolExecutor work in Java?

To use thread pools, we first create a object of ExecutorService and pass a set of tasks to it. ThreadPoolExecutor class allows to set the core and maximum pool size. The runnables that are run by a particular thread are executed sequentially.


1 Answers

I would change the behaviour of your queue. e.g.

public class MyBlockingQueue<E> extends ArrayBlockingQueue<E> {
    private final long timeoutMS;

    public MyBlockingQueue(int capacity, long timeoutMS) {
        super(capacity);
        this.timeoutMS = timeoutMS;
    }

    @Override
    public boolean offer(E e) {
        try {
            return super.offer(e, timeoutMS, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
            return false;
        }
    }
}

This will wait for the queue to drain before giving up.

like image 167
Peter Lawrey Avatar answered Sep 29 '22 16:09

Peter Lawrey