3

I'm reading about Futures and Promises in Scala and wrote the following code:

def printSomething(): Future[String] = {
  val p = Promise[String]
  val sayHello = future {
    Thread.sleep(1000)
    p.success("hello")
  }
  p.future
}

def main(args: Array[String]) {
  val something: Future[String] = printSomething()
  something onComplete {
    case Success(p) => println(p)
  }
}

The problem is the onComplete callback doesn't print anything (unless I debug it).

Wouldn't the onComplete have to wait for the p.success("hello") in the printSomething ?

Atilla Ozgur
  • 14,339
  • 3
  • 49
  • 69
Federico Lenzi
  • 1,632
  • 4
  • 18
  • 34

3 Answers3

6

My guess is that this has to do with the ExecutionContext you are using daemon threads and thus terminating when your main gets past the onComplete. If you add a sleep after the onComplete, you should get what you want. A slightly modified version of your code showing this:

import concurrent._
import ExecutionContext.Implicits._

object PromTest {
  def printSomething(): Future[String] = {
    val p = Promise[String]
    val sayHello = future {
      Thread.sleep(1000)
      p.success("hello")
    }
    p.future
  }

  def main(args: Array[String]) {
    val something: Future[String] = printSomething()
    something onComplete {
      case result => println(result)
    }
    Thread.sleep(2000)
  }
}
Community
  • 1
  • 1
cmbaxter
  • 35,283
  • 4
  • 86
  • 95
2

As other people have stated, your execution terminates before your future has had a chance to run. I feel, however, that adding a hard-coded sleep call isn't the cleanest solution, and that waiting for the future to complete (with a timeout, to prevent your code from getting stuck) is preferable:

Await.ready(something, Duration(2000, MILLISECONDS))

This will wait at most 2000 milliseconds for something to be complete, or fail otherwise.

Nicolas Rinaudo
  • 6,068
  • 28
  • 41
1

Your app exits before your promise is completed. At the end of your main method, just add something like Thread.sleep(2000) and you'll see your result.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234