Scala中的Await.result和futures.onComplete之间的区别 [英] Difference between Await.result and futures.onComplete in Scala

查看:98
本文介绍了Scala中的Await.result和futures.onComplete之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下两个代码段在多个线程中执行代码.但是我的行为有所不同.

I am using the following two code snippets to execute code in multiple threads. But I am getting different behaviour.

代码段1:

val futures = Future.sequence(Seq(f1, f2, f3, f4, f5))
futures.onComplete{
  case Success(value) =>
  case Failure(value) =>
}

代码段2:

Await.result(Future.sequence(Seq(f1, f2, f3, f4, f5)), Duration(500, TimeUnit.SECONDS))

在期货交易中,我只是设置一些属性并检索结果.

In futures I am just setting some property and retrieving the result.

注意:仅了解以上两个代码片段之间的行为差​​异就足够了.

Note: knowing only the behaviour difference between above two snippets is sufficient.

推荐答案

onCompleteExecutionContext中的某个任意(未指定)线程上运行,而Await.result在当前线程上运行并阻塞直到完成或超过了指定的超时时间.第一个是非阻塞,第二个是阻塞.

onComplete runs on some arbitrary (unspecified) thread in the ExecutionContext, whereas Await.result runs on the current thread, and blocks it until it completes or the specified timeout is exceeded. The first is non-blocking, the second is blocking.

在两个片段中处理错误的方式也有所不同,但这从查看代码中可以明显看出.

There's also a difference in how failures are handled in the two snippets, but this is kind of obvious from looking at the code.

这篇关于Scala中的Await.result和futures.onComplete之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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