Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
212 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...