创建ExecutorService并行处理任务,导致内存不足

利用ExecutorService创建的线程池并行地处理任务,可以节省总的等待时间(总等待时间等于耗时最多的那个任务的耗时)。不过线程池不会被自动地释放。所以要么创建一次线程池之后重复地使用,要么每次使用完之后显式地释放掉。不然的话最终会导致内存被用光。

问题现象:
使用Executors创建线程池批量并行处理任务(比如请求外部接口),过一段时间之后,jvm报OutOfMemory错误,进程死掉。
观察,通过jstack观察线程数,某些类型的线程一直在增长:
jstack <pid> | grep "waiting on condition" | wc -l
jstack <pid> | grep "waiting on condition"| grep pool |wc -l

问题代码(batchProcess不断被调用):
private void batchProcess(List<Integer> idList) throws Exception {
   ExecutorService executorService = Executors.newFixedThreadPool(idList.size());
   List<AreaThread> taskList = new ArrayList<>();
   for(Integer id : idList){
      taskList.add(new AreaThread(id));
   }

   List<Future<Integer>> futureList = executorService.invokeAll(taskList);

   List<Integer> resultList = new ArrayList<>();
   for(Future<Integer> future : futureList){
      Integer result = future.get();
      logger.debug("result={}", result);
      resultList.add(result);
   }
}

原因:executorService 没有被显式地关闭,线程池创建之后一直在等待新的任务,越积越多。
改正后的代码:
private void batchProcess(List<Integer> idList) throws Exception {
   ExecutorService executorService = Executors.newFixedThreadPool(idList.size());
   List<AreaThread> taskList = new ArrayList<>();
   for(Integer id : idList){
      taskList.add(new AreaThread(id));
   }

   List<Future<Integer>> futureList = executorService.invokeAll(taskList);

   List<Integer> resultList = new ArrayList<>();
   for(Future<Integer> future : futureList){
      Integer result = future.get();
      logger.debug("result={}", result);
      resultList.add(result);
   }

   executorService.shutdown(); //如果不shutdown,线程池一直不会释放
}

或者:创建一个公用的 executorService,让它一直存在,所有的批量任务都使用它。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值