Difference between Await.result and futures.onComplete in Scala

一笑奈何 提交于 2020-01-02 10:29:09

问题


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

Snippet 1:

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

Snippet 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.


回答1:


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.




回答2:


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.

On the other hand the Await blocks the thread on which the future is running until the future got completed for specific timeout.

Hence the onComplete is non blocking and Await is blocking in the nature.

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.



来源:https://stackoverflow.com/questions/50043060/difference-between-await-result-and-futures-oncomplete-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!