在Scala 2.10中杀死或使Future超时 [英] Kill or timeout a Future in Scala 2.10

查看:118
本文介绍了在Scala 2.10中杀死或使Future超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Scala 2.10与新的Futures库一起使用,并且试图编写一些代码来测试无限循环.我使用scala.concurrent.Future在单独的线程中使用循环运行代码.然后,我想稍等片刻进行测试,然后终止单独的线程/将来.我已经看过Await.result了,但这并没有杀死未来.有什么方法可以使新的Scala 2.10期货超时或终止?

I'm using Scala 2.10 with the new futures library and I'm trying to write some code to test an infinite loop. I use a scala.concurrent.Future to run the code with the loop in a separate thread. I would then like to wait a little while to do some testing and then kill off the separate thread/future. I have looked at Await.result but that doesn't actually kill the future. Is there any way to timeout or kill the new Scala 2.10 futures?

我宁愿不必为这个简单的部分添加外部依赖项(例如Akka).

I would prefer not having to add external dependencies such as Akka just for this simple part.

推荐答案

请勿在家尝试.

import scala.concurrent._
import scala.concurrent.duration._

class MyCustomExecutionContext extends AnyRef with ExecutionContext {
  import ExecutionContext.Implicits.global
  @volatile var lastThread: Option[Thread] = None
  override def execute(runnable: Runnable): Unit = {
    ExecutionContext.Implicits.global.execute(new Runnable() {
      override def run() {
        lastThread = Some(Thread.currentThread)
        runnable.run()
      }
    })
  }
  override def reportFailure(t: Throwable): Unit = ???
}    

implicit val exec = new MyCustomExecutionContext()
val f = future[Int]{ do{}while(true); 1 }
try {
  Await.result(f, 10 seconds) // 100% cpu here
} catch {
  case e: TimeoutException => 
    println("Stopping...")
    exec.lastThread.getOrElse(throw new RuntimeException("Not started"))
      .stop() // 0% cpu here
}

这篇关于在Scala 2.10中杀死或使Future超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆