简体   繁体   English

Scala中的Await.result和futures.onComplete之间的区别

[英]Difference between Await.result and futures.onComplete in Scala

I am using the following two code snippets to execute code in multiple threads. 我正在使用以下两个代码段在多个线程中执行代码。 But I am getting different behaviour. 但是我的行为有所不同。

Snippet 1: 片段1:

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

Snippet 2: 片段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. 注意:仅了解以上两个代码片段之间的行为差​​异就足够了。

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 . onCompleteExecutionContext中的某个任意(未指定)线程上ExecutionContext ,而Await.result在当前线程上运行,并阻塞它直到完成或超过指定的超时 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. 在两个片段中处理错误的方式也有所不同,但是从查看代码来看这是显而易见的。

Actually future.onComplete register a call back and wait for the result as soon as the future got completed control goes inside to the future, and see what the future has inside, it could be either success or failure. 实际上, future.onComplete注册一个回调,并在将来完成控制后将结果等待进入内部,并等待结果,然后查看未来的内在可能是成功还是失败。

On the other hand the Await blocks the thread on which the future is running until the future got completed for specific timeout. 另一方面,Await阻塞将来运行的线程,直到将来完成特定超时。

Hence the onComplete is non blocking and Await is blocking in the nature. 因此,onComplete在本质上是非阻塞的,而Await在本质上是阻塞的。

If you want to use await then try collecting as much as future you can and then do Await once you should not use Await for each and every future you have In the code it will rather slow your code. 如果要使用await,请尝试收集尽可能多的将来,然后在不应该对每个拥有的将来都使用Await的情况下执行Await。在代码中,这会降低代码的速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM