当往一个固定队列ArrayBlockingQueue 不停的提交任务时,会发生什么?

请看如下代码

 	private static final int QUEUE_SIZE = 20;
private static final int CORE_POOL_SIZE = 2;
private static final int MAX_POOL_SIZE = 2;
private static final int KEEP_ALIVE_TIME = 5; public static void main(String[] args) throws Exception {
  ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(QUEUE_SIZE));
  while(true) {
SenderTask st = new SenderTask();
executor.submit(st);
  }
  }

  

run完后会发生如下异常:

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@b99f7c6 rejected from java.util.concurrent.ThreadPoolExecutor@2959ee1d[Running, pool size = 2, active threads = 2, queued tasks = 20, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2048)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:821)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1372)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:110)

如果你有研究过executor的源码你将发现,每次在submit任务的时候,会先进行addWorker()的判断,如果不能添加成功,则会抛出RejectedExecutionException

    public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}

以上这个异常还有一种出现的情况就是,当你执行完execute.shutdown()后,任然往executor里提交task,也会抛出该异常

示例代码如下:

	public class RejectedExecutionExceptionExample {

    public static void main(String[] args) {

        ExecutorService executor = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(15));

         Worker tasks[] = new Worker[20];

        for(int i=0; i<20; i++){

           tasks[i] = new Worker(i);

           executor.execute(tasks[i]);

        }

           executor.shutdown();     

           executor.execute(tasks[0]);//继续执行任务

    }
}

如何解决呢?

1. 控制提交的任务数量,即提交的任务数量不要超过它当前能处理的能力 (这里可以用生产者消费者的模式来解决)

2. 确保不要在shutdown()之后在执行任务

3. 可以用LinkedBlockingQueue代替ArrayBlockingQueue,因为LinkedBlockingQueue可以设成无界的,但是需要注意,设成无界后最终可能发生OOM(内存溢出),

所以要保证第一二点。

参考文献:https://examples.javacodegeeks.com/core-java/util/concurrent/rejectedexecutionexception/java-util-concurrent-rejectedexecutionexception-how-to-solve-rejectedexecutionexception/

RejectedExecutionException 分析的更多相关文章

  1. Java并发(五)线程池使用番外-分析RejectedExecutionException异常

    目录 一.入门示例 二.异常场景1 三.异常场景2 四.解决方法 之前在使用线程池的时候,出现了 java.util.concurrent.RejectedExecutionException ,原因 ...

  2. zookeeper源码分析之五服务端(集群leader)处理请求流程

    leader的实现类为LeaderZooKeeperServer,它间接继承自标准ZookeeperServer.它规定了请求到达leader时需要经历的路径: PrepRequestProcesso ...

  3. 【JUC】JDK1.8源码分析之ThreadPoolExecutor(一)

    一.前言 JUC这部分还有线程池这一块没有分析,需要抓紧时间分析,下面开始ThreadPoolExecutor,其是线程池的基础,分析完了这个类会简化之后的分析,线程池可以解决两个不同问题:由于减少了 ...

  4. tomcat源码分析(三)一次http请求的旅行-从Socket说起

    p { margin-bottom: 0.25cm; line-height: 120% } tomcat源码分析(三)一次http请求的旅行 在http请求旅行之前,我们先来准备下我们所需要的工具. ...

  5. 线程池ThreadPoolExecutor、Executors参数详解与源代码分析

    欢迎探讨,如有错误敬请指正 如需转载,请注明出处 http://www.cnblogs.com/nullzx/ 1. ThreadPoolExecutor数据成员 Private final Atom ...

  6. JAVA线程池的分析和使用

    1. 引言 合理利用线程池能够带来三个好处.第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗.第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行.第三:提 ...

  7. [转]ThreadPoolExecutor线程池的分析和使用

    1. 引言 合理利用线程池能够带来三个好处. 第一:降低资源消耗.通过重复利用已创建的线程降低线程创建和销毁造成的消耗. 第二:提高响应速度.当任务到达时,任务可以不需要等到线程创建就能立即执行. 第 ...

  8. Java线程池使用和分析(二) - execute()原理

    相关文章目录: Java线程池使用和分析(一) Java线程池使用和分析(二) - execute()原理 execute()是 java.util.concurrent.Executor接口中唯一的 ...

  9. java线程池ThreadPoolExector源码分析

    java线程池ThreadPoolExector源码分析 今天研究了下ThreadPoolExector源码,大致上总结了以下几点跟大家分享下: 一.ThreadPoolExector几个主要变量 先 ...

随机推荐

  1. spring调用mongodb

    1.环境 Jdk:1.6.0_10-rc2 Spring3.1.2  下载 依赖jar文件: 2.相关配置 ①.spring配置文件 <?xml version="1.0" ...

  2. USB入门基础知识(转)

    源:USB入门基础知识 相关名词: 主机(Host) 设备(Device) 接口(Interface) 管道(Pipe) 管道是主机与设备端点数据传输的连接通道,代表了主机的数据缓冲区与设备端点之间交 ...

  3. [vue最新实战] gank客户端(vue2 + vue-router2 + vuex +webpace + es6)新手福利,干货多多

    vue-meizi 本项目是基于vue2最新实战项目,是适合新手进阶的绝佳教程.代码简单易懂,注释多多.实现了移动端使用最多的 无限滚动,图片加载,左右滑动,等待.先发布预览版本,后面更多更全的功能和 ...

  4. leetcode-004 insertion sort list

    package leetcode; class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } ...

  5. 分析java堆

    内存溢出(OutOfMemory) OOM 堆溢出 直接内存溢出 永久区溢出

  6. CreateForm(

    /// <summary> /// 打开新的子窗体 /// </summary> /// <param name="strName">窗体的类名 ...

  7. highcharts设置Y轴范围及根据Y轴范围设置不同颜色

    yAxis : { title : { text : '数据' }, plotLines : [ { value : 0, width : 1, color : '#808080' } ], min: ...

  8. Java数据流的一般操作规律总结

    流的操作规律: 1,明确源和目的. 数据源:就是需要读取,可以使用两个体系:InputStream.Reader: 数据汇:就是需要写入,可以使用两个体系:OutputStream.Writer: 2 ...

  9. 用fluent模拟内循环床气化燃烧(调试过程记录)

    模拟对象为文献Combined gasification of coal and biomass in internal circulating fluidized bed[1]中的内循环气化炉.[1]h ...

  10. Linux文件权限与目录配置

    一.linux文件属性 用户组概念:假如主机有两个团体,第一个团体名为projecta,里面有class1,class2,class3:第二个团体名为projecb,里面有class4,class5, ...