Java Stereotype Series - Thread Pool Rejection Strategy

When the task cache queue of the thread pool is full and the number of threads in the thread pool reaches the maximumPoolSize, if there are still tasks coming, the task rejection strategy will be adopted. Usually, there are the following four strategies:

  • CallerRunsPolicy: The task is processed by the calling thread (the thread that submitted the task)
  • AbortPolicy (default policy): discard the task and throw a RejectedExecutionException
  • DiscardPolicy: Discard tasks, but do not throw exceptions
  • DiscardOldestPolicy: Discard the task at the front of the queue and resubmit the rejected task

The rejection strategy needs to implement the RejectedExecutionHandler interface:

public interface RejectedExecutionHandler {
    
    

    /**
     * @param r 请求执行的可运行任务
     * @param executor 试图执行此任务的执行程序
     * @throws RejectedExecutionException 如果没有拒绝策略,则抛出该异常
     */
    void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}

The source code of the four strategies:

    /**
     * 由调用线程(提交任务的线程)处理该任务
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler {
    
    
        public CallerRunsPolicy() {
    
     }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    
    
            if (!e.isShutdown()) {
    
    
                r.run();
            }
        }
    }

    /**
     * 丢弃任务并抛出RejectedExecutionException异常
     */
    public static class AbortPolicy implements RejectedExecutionHandler {
    
    
        public AbortPolicy() {
    
     }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    
    
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
    }

    /**
     * 丢弃任务,但是不抛出异常
     */
    public static class DiscardPolicy implements RejectedExecutionHandler {
    
    
        public DiscardPolicy() {
    
     }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    
    
        }
    }

    /**
     * 丢弃队列最前面的任务,然后重新提交被拒绝的任务
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler {
    
    
        public DiscardOldestPolicy() {
    
     }

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    
    
            if (!e.isShutdown()) {
    
    
                e.getQueue().poll();
                e.execute(r);
            }
        }
    }

If you are interested in learning more about it, please visit my personal website: Yetong Space

Guess you like

Origin blog.csdn.net/tongkongyu/article/details/129360372