7

我想要一个线程安全(不可变)的 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 }

这应该可以,但是仍然有很多带有隐式参数的样板代码。(在实际代码中,我doSomething在工人类中有数百个深度嵌套的函数。)在 Scala 中有没有更漂亮的方法来做到这一点?

4

2 回答 2

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
}

编辑:blocking按照 Viktor Klang 的建议添加呼叫。

于 2013-02-04T16:24:56.260 回答
3

使用Hystrix。它是一个 Java 库,可以完全满足您的要求。与 Scala 配合得很好,并获得了很好的文档。

例子:

class LongOperation(...) extends HystrixCommand[Result](
  HystrixCommandProperties.Setter()
    .withExecutionIsolationThreadTimeoutInMilliseconds(60 * 1000))
{
  override protected def run: Result = {
    // your code
  }
}

如何同步执行:

val result = new LongOperation(...).execute()
于 2013-02-04T16:10:04.550 回答