线程池的拒绝策略(RejectedExecutionHandler)

1、AbortPolicy(线程池默认策略)

public static class AbortPolicy implements RejectedExecutionHandler {
        /**    
         * Creates an {@code AbortPolicy}.
         */
        public AbortPolicy() { }

        /**
         * Always throws RejectedExecutionException.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         * @throws RejectedExecutionException always
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            throw new RejectedExecutionException("Task " + r.toString() +
                                                 " rejected from " +
                                                 e.toString());
        }
}

    该策略是线程池的默认策略。使用该策略时,如果线程池队列满了将会丢掉这个任务并且抛出RejectedExecutionException异常(继承RuntimeException的运行时异常)。

2、DiscardPolicy

public static class DiscardPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardPolicy}.
         */
        public DiscardPolicy() { }

        /**
         * Does nothing, which has the effect of discarding task r.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        }
}

    如果线程池队列满了,将直接丢掉该任务也不会抛出任何异常。

3、DiscardOldestPolicy

public static class DiscardOldestPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code DiscardOldestPolicy} for the given executor.
         */
        public DiscardOldestPolicy() { }

        /**
         * Obtains and ignores the next task that the executor
         * would otherwise execute, if one is immediately available,
         * and then retries execution of task r, unless the executor
         * is shut down, in which case task r is instead discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                e.getQueue().poll();
                e.execute(r);
            }
        }
}

    丢弃最老的。也就是说如果队列满了,会将最早进入队列的任务删掉腾出空间,再尝试加入队列。因为队列是队尾进,队头出,所以队头元素是最老的,因此每次都是移除对头元素后再尝试入队。

4、CallerRunsPolicy

public static class CallerRunsPolicy implements RejectedExecutionHandler {
        /**
         * Creates a {@code CallerRunsPolicy}.
         */
        public CallerRunsPolicy() { }

        /**
         * Executes task r in the caller's thread, unless the executor
         * has been shut down, in which case the task is discarded.
         *
         * @param r the runnable task requested to be executed
         * @param e the executor attempting to execute this task
         */
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            if (!e.isShutdown()) {
                r.run();
            }
        }
}

    如果添加到线程池失败,那么主线程会自己去执行该任务,不会等待线程池中的线程去执行。

5、自定义拒绝策略

    实现RejectedExecutionHandler接口,并实现rejectedExecution方法。

### Java线程池拒绝策略概述 Java线程池提供了多种内置的拒绝策略来处理任务提交超出线程池容量的情况。这些策略可以通过`ThreadPoolExecutor`类进行设置,具体实现依赖于`RejectedExecutionHandler`接口。 #### 内置拒绝策略详解 1. **AbortPolicy** 默认的拒绝策略,在无法执行新任务时会抛出`RejectedExecutionException`异常[^4]。这种方式适用于希望程序立即失败并报告错误的场景。 2. **CallerRunsPolicy** 当任务被拒绝时,该策略会让提交任务的线程(即调用者线程)执行这个任务。这可能会降低系统的整体吞吐量,但在某些情况下可以缓解压力。 3. **DiscardPolicy** 静默丢弃被拒绝的任务而不做任何通知或记录。这种策略适合那些允许丢失部分任务的应用场景。 4. **DiscardOldestPolicy** 试图丢弃最旧的一个请求以便为当前任务腾出空间。此策略可能会影响较早提交的任务完成时间。 #### 自定义拒绝策略 除了上述四种标准策略外,还可以通过继承`RejectedExecutionHandler`接口来自定义拒绝逻辑。例如,`AbortPolicyWithReport`扩展了默认的`AbortPolicy`,可以在拒绝任务的同时提供额外的日志或其他操作支持[^2]。 以下是创建自定义拒绝策略的一个简单例子: ```java public class CustomRejectPolicy implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { System.err.println("Task " + r.toString() + " rejected from " + executor.toString()); // 可在此处添加其他处理逻辑,比如保存到队列或者日志记录 } } ``` #### 设置拒绝策略的方法 要在线程池中应用特定的拒绝策略,需在初始化`ThreadPoolExecutor`实例时指定它。下面是一个完整的示例代码片段展示如何配置带有不同拒绝策略线程池: ```java import java.util.concurrent.*; public class ThreadPoolExample { public static void main(String[] args) { int corePoolSize = 2; int maximumPoolSize = 4; long keepAliveTime = 10L; TimeUnit unit = TimeUnit.SECONDS; BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(2); // 创建具有CallerRunsPolicy拒绝策略线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new ThreadPoolExecutor.CallerRunsPolicy() ); // 提交超过线程池承载能力的任务数测试效果 for (int i = 0; i < 10; i++) { final int taskNumber = i; threadPool.submit(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.out.println("Executing Task " + taskNumber); }); } threadPool.shutdown(); } } ``` #### 最佳实践建议 为了更高效地利用线程池资源并减少因拒绝策略引发的问题,应遵循以下几点最佳实践: - 合理设定核心线程数(`corePoolSize`)和最大线程数(`maximumPoolSize`)以匹配实际负载需求[^3]。 - 调整阻塞队列大小(`workQueue`)以平衡内存占用与响应速度之间的关系。 - 定期监控线程池运行状况,包括活动线程计数、已完成任务总数等指标,并据此动态调整参数。 - 根据业务特点选择合适的拒绝策略;如果需要更高的灵活性,则考虑开发定制化解决方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值