当往一个固定队列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 工作原理

    1.spring原理 内部最核心的就是IOC了,动态注入,让一个对象的创建不用new了,可以自动的生产,这其实就是利用java里的反射,反射其实就是在运行时动态的去创建.调用对象,Spring就是在运 ...

  2. FZU 2099 魔法阵

    手算. #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> u ...

  3. 《玩转Bootstrap(基础)》笔记

    基本的HTML模板 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  4. 如何让搜索引擎抓取AJAX内容? 转

    越来越多的网站,开始采用"单页面结构"(Single-page application). 整个网站只有一张网页,采用 Ajax 技术,根据用户的输入,加载不同的内容. 这种做法的 ...

  5. sublime text2的插件熟悉

    今天加班,开会.于是整理下sublime text的插件. 1.安装了tag插件.负责html的格式化.从百度云下载了文件,放入了插件包的目录下. 2.启用了alignment 快捷键 ctr+alt ...

  6. Django 设置cookies与获取cookies.

    在Django里面,使用Cookie和Session看起来好像是一样的,使用的方式都是request.COOKIES[XXX]和request.session[XXX],其中XXX是您想要取得的东西的 ...

  7. [Angular Tutorial] 0-Bootstraping

    在这一节的tutorial中,您将会逐渐熟悉AngularJS phonecat app的最重要的源代码文件.您也将学到如何将开发服务器与angular-seed绑定到一起,并且在浏览器中运行应用. ...

  8. 字符集 ISO-8859-1(3)

    详细见 http://www.w3school.com.cn/tags/html_ref_urlencode.html

  9. 【HDU 5808】 Price List Strike Back (整体二分+动态规划)

    Price List Strike Back There are nn shops numbered with successive integers from 11 to nn in Bytelan ...

  10. 如何使用PDO查询Mysql来避免SQL注入风险?ThinkPHP 3.1中的SQL注入漏洞分析!

    当我们使用传统的 mysql_connect .mysql_query方法来连接查询数据库时,如果过滤不严,就有SQL注入风险,导致网站被攻击,失去控制.虽然可以用mysql_real_escape_ ...