Neeraj
Neeraj

Reputation: 8532

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

Upvotes: 7

Views: 4395

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533670

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.

Upvotes: 4

sw1nn
sw1nn

Reputation: 7328

If you have constrained your thread pool to only allow a certain number of concurrent threads (generally a good thing), then the application needs to somehow push-back on the calling code, so when you receive a RejectedExecutionException from the ThreadPoolExecutor you need to indicate this to the caller and the caller will need to handle the retry.

An analogous situation is a web server under heavy load. A client connects, the web server should return a 503 - Service Unavailable (generally a temporary condition) and the client decides what to do about it.

Upvotes: 2

Related Questions