I am learning Scala Future with the following code:
object DangerousAndSlowService {
def queryNextNumber: Long = {
50
}
}
val number1F = Future { DangerousAndSlowService.queryNextNumber }
number1F.onComplete({
case Success(value) => {
println(s"Got the callback, meaning = $value")
}
case Failure(exception) => {
exception.printStackTrace
}
})
However, the "50" is never printed.
Already spent several hours but still cannot figure it out.
Thanks.
The main thread exits without letting the future finish its job, therefore the output is non-deterministic: sometimes it does print something, sometimes it doesn't. If you don't mind blocking the main thread, you can use Await
:
import scala.concurrent.Future
import scala.util.{Success, Failure}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Await
import scala.concurrent.duration._
object DangerousAndSlowService {
def queryNextNumber: Long = {
50
}
}
val number1F = Future { DangerousAndSlowService.queryNextNumber }
number1F.onComplete({
case Success(value) => {
println(s"Got the callback, meaning = $value")
}
case Failure(exception) => {
exception.printStackTrace
}
})
Await.result(number1F, 1.second)
While Await
is necessary here to produce the output, it's also good to note you should use it with caution. It blocks the current thread, which is typically not what you want when you work with asynchronous computations and futures.