Skip to content

Memory leaks when calling Future.flatMap #7336

Closed

Description

@scabug

Following up this thread: https://groups.google.com/forum/?fromgroups=#!topic/play-framework-dev/58VZD-YXdJw

Using a lot of flatMap calls leaks. Here is a snippet of code that shows the problem:

import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
import scala.util._

object FutureLeak extends App {
val step = 100000
val upper = 1000000

// code that leaks
def loop(future: Future[Int]): Future[Int] = {
future.flatMap { i =>
if (i % step == 0) println(i)
if (i < upper)
loop(Future(i + 1))
else Future(i)
}
}

// code that does not leak
def loop2(future: Future[Int]): Future[Int] = {
val promise = Promise[Int]

def inloop(future: Future[Int]): Unit = {
  future.onComplete {
    case Success(i) if i < upper =>
      if (i % step == 0) println(i)
      inloop(Future(i + 1))
    case Success(i) =>
      println("done with " + i)
      promise.success(i)
  }
}

inloop(future)
promise.future

}

Await.result(loop(Future(0)), 100 seconds) // leads to java.lang.OutOfMemoryError: Java heap space with -Xms32m -Xmx32m

Await.result(loop2(Future(0)), 100 seconds) // runs fine with -Xms32m -Xmx32m
}

It should not leak since the produced futures do not depend on each other.

Activity

  1. scabug commented on Apr 5, 2013

    @scabug
    Author

    Imported From: https://issues.scala-lang.org/browse/SI-7336?orig=1
    Reporter: Stephane Godbillon (sgodbillon)
    Affected Versions: 2.10.0, 2.10.1
    See #7493

  2. scabug commented on Jul 12, 2013

    @scabug
    Author
  3. added this to the 2.10.3-RC1 milestone on Apr 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions