Scala - futures does not run

感情迁移 提交于 2019-12-23 16:54:00

问题


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....


回答1:


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 )
}


来源:https://stackoverflow.com/questions/16358064/scala-futures-does-not-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!