How to handle RejectedExecutionException using ThreadPoolExecutor in java

What is the best processing method RejectedExecutionExceptionwhen used ThreadPoolExecutorin Java?

I want to make sure that the task should not be missed and must be carried out. At the moment, there are no strict requirements for real time to complete the task.

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

I would be glad if people can share their experiences.

Adding a possible solution, although I:

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));
+5
source share
2 answers

I would change the behavior of your queue. eg.

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

, , .

+3

, ( , ), - , , RejectedExecutionException ThreadPoolExecutor, , .

- . , - 503 - Service Unavailable ( ), , .

+2

All Articles