【发布时间】: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