ExecutorService 关闭 - Kafka

ExecutorService Shutdown - Kafka

我正在从 Kafka 获取消息并使用类似于下面的 Executor 服务处理它们。我没有调用 executorService.shutdown()。我偶尔会看到 heapSize exception ,但不确定这是否是原因之一。完成后如何删除未使用的 Runnable 实例?我是否应该做任何具体的事情来明确使其符合 GC 的条件?

public class Consumer implements CommandLineRunner{

    ExecutorService executorService;
    executorService = Executors.newFixedThreadPool(50)
    executorService.submit(runnable);

  }
}

来自 Executors.newFixedThreadPool 的文档:

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

对于给定的示例,线程池中最多有 50 个线程处于活动状态,当您调用 shutdown 方法时,它们将被释放。

如果您不保留对 Runnable 的引用,当 Executor 处理完它们时,它们将被 GC 处理。如果出现内存不足异常,这可能是由于排队 Runnables 在执行者跟不上提交给他的工作的情况下。

编辑:如果您的任务占用大量内存(显然),也会发生内存不足异常。