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

版权声明:本文为原创文章,转载请注明转自Clement-Xu的csdn博客。 https://blog.csdn.net/ClementAD/article/details/75663956
利用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,让它一直存在,所有的批量任务都使用它。

猜你喜欢

转载自blog.csdn.net/ClementAD/article/details/75663956