Search code examples
javajava.util.concurrentthreadpoolexecutor

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.


Solution

  • Yes it is possible to retry the execution of the rejected task. The best way to retry the execution is to use an alternate executor. You may declare a custom RejectedExecutionHandler class simply like as you do this with other interfaces. Here are some code samples:

    public class MyRejectedExecutionHandler implements RejectedExecutionHandler {
    
    
    
    @Override
    public void rejectedExecution(Runnable worker, ThreadPoolExecutor executor) {
        // TODO Auto-generated method stub
        System.out.println(worker.toString()+" is Rejected");
    
        System.out.println("Retrying to Execute");
        try{
            //Re-executing with alternateExecutor
            MainClass.alternateExecutor.execute(worker);
            System.out.println(worker.toString()+" Execution Started");
        }
        catch(Exception e)
        {
            System.out.println("Failure to Re-exicute "+e.getMessage());
        }
    }
    
    }
    

    You can find more details about this at: http://examples.javacodegeeks.com/core-java/util/concurrent/rejectedexecutionhandler/java-util-concurrent-rejectedexecutionhandler-example/