加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 异常导致Future永远不会完成

发布时间:2020-12-16 18:41:49 所属栏目:安全 来源:网络整理
导读:给出以下代码: import scala.concurrent.ExecutionContextimport java.util.concurrent.Executorsval ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(1))val f = Future[Unit](throw new java.lang.InternalError())(ec) 未来永远不会完
给出以下代码:

import scala.concurrent.ExecutionContext
import java.util.concurrent.Executors

val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(1))

val f = Future[Unit](throw new java.lang.InternalError())(ec)

未来永远不会完成. f.value始终为None.

scala-2.10中有一个已知错误已被修复:

http://mandubian.com/2013/02/22/scala-future-fatal-exception

https://issues.scala-lang.org/browse/SI-7029

我在scala-2.11上.

错误报告中的示例使用NotImplementedErorr,它由Future正确处理,它将完成.但是,如果我在上面的示例中使用InternalError,那么Future永远不会完成.无论我使用ExecutionContext.global,Executors.newSingleThreadExecutor还是Executors.newFixedThreadPool,都是如此.

我可以在未来的身体中抓住Throwable并重新抛出它,并且我知道Future会正确处理它,但这是一个可怕的解决方案.

这是一个已知的问题?预期的行为?我有什么选择可以从我的期货中获得理智的行为?

解决方法

来自 Future的来源.

override def run() = {
  promise complete {
    try Success(body) catch { case NonFatal(e) => Failure(e) }
  }
}

如您所见,Future只捕获NonFatal异常.

以下是NonFatal匹配的内容.

def apply(t: Throwable): Boolean = t match {
  // VirtualMachineError includes OutOfMemoryError and other fatal errors
  case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
  case _ => true

}

由于java.lang.InternalError是VirtualMachineError的子类,运行任务的线程只是被异常杀死,并且承诺永远不会完成.

从exceptions in the future的概述

Fatal exceptions (as determined by NonFatal) are rethrown in the thread executing the failed asynchronous computation. This informs the code managing the executing threads of the problem and allows it to fail fast,if necessary. See NonFatal for a more precise description of the semantics.

因此我认为这是预期的行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读