Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use custom RejectedExecutionHandler

While using java.util.concurrent.ThreadPoolExecutor I wanted to try to execute a rejected task once more. Is it really possible? I have heard of RejectedExecutionHandler interface. There are many available(known) instances of the interface(RejectedExecutionHandler) such as ThreadPoolExecutor.AbortPolicy, ThreadPoolExecutor.CallerRunsPolicy, ThreadPoolExecutor.DiscardOldestPolicy, ThreadPoolExecutor.DiscardPolicy etc. but the problem is that they do not allow to retry the execution.

like image 707
Rivu Chakraborty Avatar asked May 01 '26 08:05

Rivu Chakraborty


1 Answers

Below is a retry-enabled RejectedExecutionHandler that does not require an additional ThreadPoolExecutor. It's is more practical: when a task was rejected, the rejected task will be put into the workerQueue of ThreadPoolExecutor in blocking mode, which makes the task submitter wait some time before the ThreadPoolExecutor can process any more tasks.

new RejectedExecutionHandler() {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            if (!executor.isShutdown()) {
                try {
                    executor.getQueue().put(r);
                } catch (InterruptedException e) {
                    ;
                }
            }

        }

    }
like image 193
Viscent Huang Avatar answered May 02 '26 21:05

Viscent Huang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!