ThreadPoolTaskExecutor遇到的坑

比眉伴天荒 2022-04-17 02:40 596阅读 0赞

在利用org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor实现请求的慢处理时,我的配置中核心线程数为5,最大线程数为10,但是代码中创建了8个队列放在线程池中,假如我用idhash取模,得到队列集合下标,将数据放到集合的队列中,此时就会出现8个队列中,每个队列都有数据,但只有前5个队列中的请求被处理,后3个队列的请求被搁置。
因此,配置线程池的线程最少数量时,一定要大于等于自己创建的队列数量。
出现此问题的真正原因:
如果队列满了,并且已创建的线程数小于最大线程数,则线程池会再创建新的线程执行任务。如果使用了无界的任务队列这个参数就没什么效果

关键配置及代码:

  1. <bean id="deviceBindExecutor" name="deviceBindExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
  2. <!-- 线程池维护线程的最少数量 -->
  3. <property name="corePoolSize" value="5" />
  4. <!-- 允许的空闲时间 -->
  5. <property name="keepAliveSeconds" value="200" />
  6. <!-- 线程池维护线程的最大数量 -->
  7. <property name="maxPoolSize" value="10" />
  8. <!-- 线程池阻塞队列大小 -->
  9. <property name="queueCapacity" value="10" />
  10. <!-- 对拒绝task的处理策略 -->
  11. <property name="rejectedExecutionHandler">
  12. <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
  13. </property>
  14. </bean>

代码实现如下:

  1. /**
  2. * 懒汉式单例可以实现传参的单例初始化
  3. */
  4. public class RequestProcessorThreadPool {
  5. private volatile static RequestProcessorThreadPool instance = null;
  6. private RequestProcessorThreadPool() {
  7. }
  8. private RequestProcessorThreadPool(ApplicationContext applicationContext) {
  9. RequestQueue requestQueue = RequestQueue.getInstance();
  10. ThreadPoolTaskExecutor threadPool = (ThreadPoolTaskExecutor) applicationContext.getBean("deviceBindExecutor");
  11. /**
  12. * 给线程池中加入任务队列
  13. */
  14. for (int i = 0; i < 8; i++) {
  15. ArrayBlockingQueue<Request> queue = new ArrayBlockingQueue<Request>(100);
  16. requestQueue.addQueue(queue);
  17. threadPool.submit(new RequestProcessorThread(queue));
  18. }
  19. }
  20. public static RequestProcessorThreadPool getInstance(ApplicationContext applicationContext) {
  21. if (instance == null) {
  22. synchronized (RequestProcessorThreadPool.class) {
  23. if (instance == null) {
  24. instance = new RequestProcessorThreadPool(applicationContext);
  25. }
  26. }
  27. }
  28. return instance;
  29. }
  30. }

发表评论

表情:
评论列表 (有 0 条评论,596人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Linux遇到

    最近换了一个电脑  新安装了一个linux   装在虚拟机下   具体的安装过程则合理不在赘述 讲讲安装之后发现的问题吧  首先是没有汉字  重新下载安装  这个不复杂

    相关 Xposed遇到

    如果某个APP的dex有多个在安卓5,0以上ART会合成一个oat文件。那么5.0以下会存在多个dex。 所以在5.0以下hook一个某个方法,而这个方法不在主dex,而存

    相关 Hibernate 遇到

    传统的java开发中,通常分领域模型,model。在对数据进行保存的时候通常一般会保存到vo中,显示数据到页面的时候通常是dto,前几天遇到个坑,在dto中封装实体对象,...