【问题标题】:too many threads by CachedThreadPool?CachedThreadPool 线程过多?
【发布时间】:2018-09-10 14:51:39
【问题描述】:

我有以下代码:

val executor = Executors.newScheduledThreadPool(4)

val futures = dataToProcess flatMap {
        case (name, dataByDate) =>
          dataByDate map {
            case (date, data) =>
              (name, date, data) -> executor.submit(new Callable[ProcessResult] {
                override def call() = {
                  val result = processor.process(...)
                  persist(result, name, date, data)
                  result
                }
              })
          }
      }

processor.process() 中,一些线程池(Executors.newFixedThreadPool(64))用于处理数据。 这些线程池不是动态创建的

在上面的代码中,我们得到了大约 100K 的以下错误: ... Exception in thread "Thread-129359954" java.lang.OutOfMemoryError: unable to create new native thread Exception in thread "Thread-129359959" java.lang.OutOfMemoryError: unable to create new native thread Exception in thread "Thread-129359963" java.lang.OutOfMemoryError: unable to create new native thread Exception in thread "Thread-129359966" java.lang.OutOfMemoryError: unable to create new native thread Exception in thread "Thread-129359970" java.lang.OutOfMemoryError: unable to create new native thread Exception in thread "Thread-129359978" java.lang.OutOfMemoryError: unable to create new native thread ....

我不知道为什么要创建这么多线程。欢迎任何cmets。谢谢。

更新

我发现在 contextInitialized() 的 Java Web 应用程序代码库中,创建了一些线程池(Executors.newCachedThreadPool()Executors.newScheduledThreadPool(1))并在许多情况下重复使用。 shutdown() 没有在contextDestroyed() 中显式调用。如果这些线程池没有明确关闭会发生什么。我想知道这是否是这么多线程的原因。

【问题讨论】:

  • 不要动态创建线程池和执行器。只需让您的处理器使用您在顶层创建的相同执行器。
  • 那个数字 129362014 可能不是序列号。不要以为这意味着你的程序已经创建了超过一亿个线程。该数字最有可能来自 Thread 对象的虚拟内存地址。

标签: java multithreading scala threadpool threadpoolexecutor


【解决方案1】:

一旦你的执行完成,线程就会返回到池中。即使你关闭了,我认为你仍然在并行创建太多的执行器服务。关机将等待所有任务完成。所以你会有资源争用。

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2012-09-25
    相关资源
    最近更新 更多