加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala Infinite Iterator OutOfMemory

发布时间:2020-12-16 18:11:10 所属栏目:安全 来源:网络整理
导读:我正在玩 Scala的懒惰迭代器,我遇到了一个问题.我要做的是读取一个大文件,进行转换,然后写出结果: object FileProcessor { def main(args: Array[String]) { val inSource = Source.fromFile("in.txt") val outSource = new PrintWriter("out.txt") try { /
我正在玩 Scala的懒惰迭代器,我遇到了一个问题.我要做的是读取一个大文件,进行转换,然后写出结果:

object FileProcessor {
  def main(args: Array[String]) {
    val inSource = Source.fromFile("in.txt")
    val outSource = new PrintWriter("out.txt")

    try {
      // this "basic" lazy iterator works fine
      // val iterator = inSource.getLines

      // ...but this one,which incorporates my process method,// throws OutOfMemoryExceptions
      val iterator = process(inSource.getLines.toSeq).iterator

      while(iterator.hasNext) outSource.println(iterator.next)

    } finally {
      inSource.close()
      outSource.close()
    }
  }

  // processing in this case just means upper-cases every line
  private def process(contents: Seq[String]) = contents.map(_.toUpperCase)
}

所以我在大文件上得到一个OutOfMemoryException.我知道如果你保持对流的头部的引用,你可以与Scala的懒惰流相遇.所以在这种情况下,我小心翼翼地将process()的结果转换为迭代器并抛弃最初返回的Seq.

有谁知道为什么这仍会导致O(n)内存消耗?谢谢!

更新

为了回应fge和huynhjl,似乎Seq可能是罪魁祸首,但我不知道为什么.作为一个例子,以下代码工作正常(我在整个地方使用Seq).此代码不会产生OutOfMemoryException:

object FileReader {
  def main(args: Array[String]) {

  val inSource = Source.fromFile("in.txt")
  val outSource = new PrintWriter("out.txt")
  try {
    writeToFile(outSource,process(inSource.getLines.toSeq))
  } finally {
    inSource.close()
    outSource.close()
  }
}

@scala.annotation.tailrec
private def writeToFile(outSource: PrintWriter,contents: Seq[String]) {
  if (! contents.isEmpty) {
    outSource.println(contents.head)
    writeToFile(outSource,contents.tail)
  }
}

private def process(contents: Seq[String]) = contents.map(_.toUpperCase)

解决方法

正如fge暗示的那样,修改进程以获取迭代器并删除.toSeq. inSource.getLines已经是一个迭代器.

转换为Seq将导致记住项目.我认为它会将迭代器转换为Stream并导致所有项目都被记住.

编辑:好的,它更加微妙.您通过在进程的结果上调用迭代器来执行Iterator.toSeq.iterator的等效操作.这可能会导致内存不足异常.

scala> Iterator.continually(1).toSeq.iterator.take(300*1024*1024).size
java.lang.OutOfMemoryError: Java heap space

这可能与此处报告的问题相同:https://issues.scala-lang.org/browse/SI-4835.请注意我在错误结尾处的评论,这是来自个人经验.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读