如何在 Scala 中取消 Future? [英] How to cancel Future in Scala?

查看:28
本文介绍了如何在 Scala 中取消 Future?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java Future取消 方法,该方法可以中断运行 Future 任务的线程.例如,如果我将 interruptible 阻塞调用包装在 Java Future 中,我可以稍后中断它.

Java Future has cancel method, which can interrupt the thread, which runs the Future task. For example, if I wrap an interruptible blocking call in a Java Future I can interrupt it later.

Scala Future 不提供cancel 方法.假设我在 Scala Future 中包装了一个 interruptible 阻塞调用.我怎么能打断它?

Scala Future provides no cancel method. Suppose I wrap an interruptible blocking call in a Scala Future. How can I interrupt it?

推荐答案

这还不是 Future 的 API 的一部分,但将来可能会作为扩展添加.

This is not yet a part of the Futures API, but may be added as an extension in the future.

作为一种解决方法,您可以使用 firstCompletedOf 来包装 2 个期货 - 您要取消的期货和来自自定义 Promise 的期货.然后,您可以通过使承诺失败来取消由此创建的未来:

As a workaround, you could use the firstCompletedOf to wrap 2 futures - the future you want to cancel and a future that comes from a custom Promise. You could then cancel the thus created future by failing the promise:

def cancellable[T](f: Future[T])(customCode: => Unit): (() => Unit, Future[T]) = {
  val p = Promise[T]
  val first = Future firstCompletedOf Seq(p.future, f)
  val cancellation: () => Unit = {
    () =>
      first onFailure { case e => customCode}
      p failure new Exception
  }
  (cancellation, first)
}

现在你可以在任何未来调用它来获得一个可取消的包装器".示例用例:

Now you can call this on any future to obtain a "cancellable wrapper". Example use-case:

val f = callReturningAFuture()
val (cancel, f1) = cancellable(f) {
  cancelTheCallReturningAFuture()
}

// somewhere else in code
if (condition) cancel() else println(Await.result(f1))

有关取消的详细讨论,请参阅 中的第 4 章在 Scala 中学习并发编程一书.

For a detailed discussion on cancellation, see Chapter 4 in the Learning concurrent programming in Scala book.

这篇关于如何在 Scala 中取消 Future?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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