在 java 中使用执行器时出现内存不足错误

Out of Memory Error when using Executors in java

我正在使用 Executors 框架(具有无限阻塞队列的固定线程池)并发执行任务。

但是当我运行创建了大约 10000 个任务的负载测试时,堆内存 (2.1 GB) 大量增加,其中包含大约 350 万个可执行对象。

我不确定无限队列是否导致了这种堆积。

内存分析器报告:

One instance of "java.util.concurrent.ThreadPoolExecutor" loaded by "" occupies 2,299,506,584 (94.97%) bytes. The instance is referenced by com.test.ScheduleBean @ 0x743592b28 , loaded by "org.jboss.modules.ModuleClassLoader @ 0x741b4cc40".

感谢任何指点!

        //The Executors are loaded in a hashmap
        HashMap<String,Executor> poolExecutorMap = new HashMap<String,Executor>();

       //Executor is a fixed thread pool one
       Executor poolExecutor = Executors.newFixedThreadPool(threadCount);

      //then add the executor to the hashmap
       poolExecutorMap.put("Executor", poolExecutor);



    //then a list of tasks are pulled from a database and passed as runnable objects to the executors

      Class<?> monitorClass=null;

      List<Task> list = getAllTasksToProcess();

     for (int i = 0; i < list.size(); i++) {
      Task task = list.get((int) i);

     monitorClass = Class.forName(task.getTask_event_name());
        Constructor<?> ctor;
        ctor = monitorClass.getConstructor(Task.class);
        Object object = ctor.newInstance(task);
        logger.debug("Adding  task number : "+task.getTask_sequence_id());
        poolExecutorMap.get("Executor").execute((Runnable) object);
}



// the executor classes have an execute method which sends a http notification.

在 MemoryAnalyzerTool 中编写 OQL

select * 来自 java.util.concurrent.ThreadPoolExecutor

并执行查询。它将在单独的 window 中列出对象。 然后右键单击生成的实例然后

GC 根路径 --> 排除 soft/weak/phantom 个引用

这将帮助您了解谁持有可疑对象的强引用。

感谢大家的回复。

真正的问题是从数据库中提取任务的方式。 重复的任务被添加到任务队列,因此队列建立起来。