我只是试着让我的第一个期货用完并运行,并做一个类似于书中概述的一个例子的测试。我想调用一个web服务并在将来返回结果。我正在使用scalaxb访问web服务。我已经概述了下面的代码,但是当我运行它时,应用程序就会终止,而无需等待服务的响应。也许有人能告诉我我错过了什么?
import scala.util._
import control.NonFatal
import scala.concurrent._
import ExecutionContext.Implicits.global
object Test {
val service = (new MyServiceBindings with scalaxb.Soap11Clients with scalaxb.DispatchHttpClients {}).service
def test = {
val f = future {
service.someCall() match {
case Right(resp) => resp
case Left(fault) => throw new Exception("Fault: " + fault)}
}
}
f.onComplete {
case Success(resp) => println("Resp: " + resp)
case Failure(NonFatal(e)) => println("Fail: " + e)
}
}
def main(args: Array[String]): Unit = {
test
}
}发布于 2014-05-08 17:40:47
它的终止是因为在您的测试中执行的主线程已经完成。调度库内部使用的线程不会阻止程序退出。
您需要等待未来,因为这是您的测试应用程序正在做的唯一事情。把这个放在onComplete语句之后。
import scala.concurrent.duration._ Await.ready(f, 10.seconds)
现在请记住,这通常是不好的做法。你在这里需要它,因为你的测试应用程序不做任何其他事情,但是在一个真正的应用程序中,你不想在每次期货调用之后阻塞,因为这将否定使用期货的意义。
发布于 2015-06-01 13:56:53
可以通过在测试应用程序中添加以下逻辑来修补主函数中的这个问题:
def main(args: Array[String]) : Unit = {
// Assuming test is a future that did not complete yet.
while(!test.isCompleted) {
Thread.sleep(100)
}
// Software exits here only after future is completed.
}或更好,如果您有许多未来,您可以这样实现它:
//假设您已经-> listOfFutures = ArrayBufferFuture
def main(args: Array[String]) : Unit = {
while(!listOfFutures.isEmpty) {
listOfFutures.foreach {
future =>
if(future.isCompleted) {
listOfFutures -= future
}
}
//checks which futures are completed every half-a-second
Thread.sleep(500)
}
// Program exits after all futures have been completed.
}https://stackoverflow.com/questions/23547963
复制相似问题