线程池ThreadPoolExecutor拒绝策略RejectedExecutionHandler

引子问题

问题1:什么时候触发拒绝策略?

问题2:拒绝策略有哪些?

问题3:默认的拒绝策略是什么?

问题4:你实际开发经历中的拒绝策略是什么?

创建线程池

核心线程数、最大线程数、空闲存活时间根据业务决定

任务队列避免使用无界队列,以免产生OOM

        int coreSize = 4;
        int maximumPoolSize = 8;
        long keepAliveTime = 5;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(20);
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor pool = new ThreadPoolExecutor(coreSize,maximumPoolSize,keepAliveTime,unit,workQueue,handler);
        

拒绝策略有哪些

严格来说,只要实现了RejectedExecutionHandler接口的,都可以作为拒绝策略,这里讨论的是JUC自带的拒绝策略。

上源码……

package java.util.concurrent;

/**
 * A handler for tasks that cannot be executed by a {@link ThreadPoolExecutor}.
 *
 * @since 1.5
 * @author Doug Lea
 */
public interface RejectedExecutionHandler {

    /**
     * Method that may be invoked by a {@link ThreadPoolExecutor} when
     * {@link ThreadPoolExecutor#execute execute} cannot accept a
     * task.  This may occur when no more threads or queue slots are
     * available because their bounds would be exceeded, or upon
     * shutdown of 
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值