处理不可变类中的超时

Son*_*123 7 timeout scala immutability thread-safety

我想要一个线程安全(不可变)的Scala类来完成一项长期工作.对于某些极端情况,任务需要很长时间,所以我想实现超时.在不可变类中实现它的最佳方法是什么?

我的第一次尝试是使用这样的隐式参数:

class Worker(val input: String) {

  def start: String = {
    implicit val startTimeStamp = new TimeStamp
    doSomething1 + doSomething2
  }

  def doSomething1()(implicit startTimeStamp: TimeStamp): String = { ... }

  def doSomething2()(implicit startTimeStamp: TimeStamp): String = {
    ... 
    checkTimeout 
    ...
   }
}

class TimeStamp { val start = System.currentTimeMillis }
Run Code Online (Sandbox Code Playgroud)

这应该有效,但仍有很多带有隐含参数的样板代码.(在实际代码中,我doSomething在worker类中有数百个深层嵌套函数.)在Scala中有更好的方法吗?

dre*_*xin 5

听起来你正在寻找未来.在scala 2.9.x中我建议你使用akka库,从2.10.0开始就有这个scala.concurrent.Future特性.

2.10的示例:

import concurrent._
import concurrent.duration._
import ExecutionContext.Implicits.global

val f = future {
  blocking {
    // long running task
  }
}

try {
  val res = Await.result(f, 100 millis)
} catch {
  case e: java.util.concurrent.TimeoutException =>
    // handle timeout
}
Run Code Online (Sandbox Code Playgroud)

编辑:blocking Viktor Klang建议添加的电话.

  • 如果您将来要进行长时间运行,则应将其包装在"阻塞"调用中,以便至少通知底层的ExecutionContext线程将被占用一段时间:http:// www.scala-lang.org/api/current/index.html#scala.concurrent.package (2认同)