简体   繁体   中英

Scala Future not printing results

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM