4

I am trying to run the following future basic code

 future { println("ssss")} onSuccess{ case _ => println("succ")}

However, when I run the main method, nothing to the console is printed and the system exits almost instantly. I am using the implicit ExecutionContext. Any hints?

This code:

  val f = future(Await.ready(Promise().future, d.timeLeft))

   f.onSuccess {
     case _ => println("hee")
   }

also exits immediately....

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Bober02
  • 15,034
  • 31
  • 92
  • 178
  • 2
    possible duplicate of [Possible bug in Scala 2.10 future](http://stackoverflow.com/questions/10565475/possible-bug-in-scala-2-10-future) – Dylan May 03 '13 at 12:23

1 Answers1

12

Futures are executed on a dedicated thread pool. If your main program does not wait for the future, it will exit immediately and the future won't have a chance to execute. What you can do here is to use Await in your main program to block the main thread until the future executes:

def main( args: Array[String] ) {
  val fut = future { println("ssss")}
  fut onSuccess{ case _ => println("succ")}
  Await.result( fut )
}
Régis Jean-Gilles
  • 32,541
  • 5
  • 83
  • 97
  • I would basically like the Java future.get() blocking behavior in Scala, is that achieved using Await? – Bober02 May 03 '13 at 11:45
  • Yes, this will wait for the result and return it (or rethrow the exception if the future failed). – Régis Jean-Gilles May 03 '13 at 11:47
  • So what is the point of OnSuccess if it runs on the separate thread and does not propagate the result until we actually ask for results? We could have simply ask for results on the main thread and then perform sth based on success/failure, correct? – Bober02 May 03 '13 at 12:55
  • 1
    In this simple case, there is no point, much like spawning a thread just to indefinitely wait for it (through `Thread.join`) is useless. The reasons to use futures are mostly the same as the reasons to use threads. But futures have the added advantage to be much more easily composable, to be a simpler abstraction and to scale much better than raw threads (or equivalently, if you already use thread pools). – Régis Jean-Gilles May 03 '13 at 14:02