Scala - 未来的“内存不足”
Posted
技术标签:
【中文标题】Scala - 未来的“内存不足”【英文标题】:Scala - Future "Out of memory" 【发布时间】:2021-12-08 15:24:07 【问题描述】:所以我必须遵循以下代码:
case class ResultEntry(destination: String,
from: LocalDate,
to: LocalDate,
data: Data)
val destinations = Seq(
"New York",
"Scranton",
"Stamford",
"Jamaica",
)
val dates = 0.to(30).map(v => LocalDate.of(2021, 1, 1).plusDays(v))
Await.result(
Future
.sequence(for
destination <- destinations
fromDate <- dates
toDate <- dates if (toDate.isAfter(fromDate))
score = Future(
blocking(
SnelDwight.calculateVacationScore(destination, fromDate, toDate)))
yield
score.map score =>
ResultEntry(destination, fromDate, toDate, score)
)
.map results =>
results.groupBy(_.destination).map
case (destination, results) =>
val min = results.minBy(_.data.score)
println(s"$destination : $min")
,
Duration.Inf
)
此代码将引发“内存不足”异常。我需要解决这个问题,但要尽可能保持计算并发。我怎样才能做到这一点?
【问题讨论】:
【参考方案1】:使用blocking
每次都会创建一个新线程,而不是使用线程池中的现有线程。这样可以避免阻塞池中的每个线程并阻止新的Future
s 运行的危险。
在此示例中,您创建了近 2,000 个线程,这很可能会导致内存错误。
如果计算没有真正阻塞,那么只需删除 blocking
。
如果计算 阻塞,那么您需要在单个线程上批处理多个计算。例如,在一个Future
中执行所有toDate
s(无论如何这可能更有效)。
【讨论】:
你能给我看一个toDate
的代码示例吗?以上是关于Scala - 未来的“内存不足”的主要内容,如果未能解决你的问题,请参考以下文章