0

Using Scala-IDE 3.0.3 (based on Scala 2.10.4), the following code completes correctly by displaying the first 10 values of the computed List from a future as well as the Future completedmessage:

import scala.concurrent._
import scala.concurrent.duration._
import scala.util.{Failure, Success}
import ExecutionContext.Implicits.global

object FutureNonBlocking extends App {

    val f1: Future[List[Int]] = future {
        val t = List.range(1, 50).filter(_ % 2 == 0)
        println("Done")
        t
    }

    f1.onComplete {
        case Success(value) => println(value.take(10))
        case Failure(e) => println("Something bad happened")
    }

    Await.complete(f1, 30 seconds)
}

However, changing the range List.range(1, 50) to List.range(1, 5000) does not display anything and (the Failure is not triggered). Logically, it seems to be related to a memory issue but I don't understand what is happening there.

Even stranger, running this code in a REPL does not cause the issue. What am I missing there?

pmudry
  • 66
  • 6
  • I try this in repl, and found everything ok. – jilen Apr 14 '14 at 10:21
  • Seems to be working in my 2.10.3 REPL as well. The problem was seen in Scala-IDE 3.0.3-20140327, which is using Scala 2.10.4. Which version of Scala were you using? – pmudry Apr 14 '14 at 10:35
  • I tried in a 2.10.4 REPL and this also works as expected. This seems then tied to Scala-IDE itself but I can't imagine why. Editing question accordingly. – pmudry Apr 14 '14 at 10:42
  • 1
    If the app already stopped after run. Then I guess the console output is lost. Eclipse sometimes seems cannot display all console output in multi threading env. You try print that to a file and see the result. – jilen Apr 14 '14 at 10:52
  • This is it! Just adding a `Thread.sleep(1000)` to wait a bit solved the case. Thank you very much, I was afraid something odd was happening behind the scenes! – pmudry Apr 14 '14 at 10:59
  • This is particularly a problem for the Eclipse Scala Worksheet - concurrent code often needs a sleep() at the end to keep the process alive long enough to see the output. – DNA Apr 14 '14 at 15:00

1 Answers1

3

It turns out the whole thing is not an issue with memory management in Futures but it is related to the way Eclipse handles console output for concurrent programs.

Adding Thread.sleep(1000) at the end of the program let Eclipse show all the console output, solving the problem.

Thank you very much @jilen for your very helpful comment!

pmudry
  • 66
  • 6
  • 1
    Await.ready(f1) only wait for f1 to complete, things in `f1.onComplete` may not executed yet. If you use the `transform` to create a new future and await for that future, things will be ok – jilen Apr 15 '14 at 00:38
  • Thank you for pointing that out, this was a mistake. I have changed the original question to reflect this. – pmudry Apr 17 '14 at 12:46