Ste*_*han 9 timeout scala future scala-2.10
嗨,
我正在使用Scala 2.10和新的期货库,我正在尝试编写一些代码来测试无限循环.我使用a scala.concurrent.Future
在单独的线程中使用循环运行代码.然后我想等一会儿做一些测试,然后杀死单独的线程/未来.我已经看过,Await.result
但实际上并没有杀死未来.有没有办法超时或杀死新的Scala 2.10期货?
我宁愿不必为这个简单的部分添加外部依赖项,如Akka.
不要在家尝试.
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4196 次 |
最近记录: |