3

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.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
avy
  • 417
  • 1
  • 9
  • 21
  • just the mandatory advice: you should never use Await in production code. Use it only for testing porpoises. – RoberMP Apr 26 '18 at 14:59

2 Answers2

2

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.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
  • what means the current thread. does it means the single thread of OS? and also blocking means other thread will execute after the current ? – avy Apr 26 '18 at 13:06
  • No, there is no such thing as "single thread of OS", unless you are using a weird embedded operating system. The current thread means the thread the `Await.result` method is being called from. Blocking means the next statement/expression will be evaluated only after the thread has unblocked; non-blocking means "next" (not really next) statement/expression will be evaluated on another thread, so it doesn't block the current thread. – Robin Green Apr 26 '18 at 13:09
0

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.

Raman Mishra
  • 2,635
  • 2
  • 15
  • 32