Suppose I need to run a few concurrent tasks.
I can wrap each task in a Future
and wait for their completion. Alternatively I can create an Actor
for each task. Each Actor
would execute its task (e.g. upon receiving a "start" message) and send the result back.
I wonder when I should use the former (with Future
s) and the latter (with Actor
s) approach and why the Future
approach is considered better for the case described above.
Because it is syntactically simpler.
val tasks: Seq[() => T] = ???
val futures = tasks map {
t => future { t() }
}
val results: Future[Seq[T]] = Future.sequence(futures)
The results
future you can then wait on using Await.result
or you can map it further/use it in for-comprehension or install callbacks on it.
Compare that to instantiating all the actors, sending messages to them, coding their receive
blocks, receiving responses from them and shutting them down -- that would generally require more boilerplate.
I tend to think that actors are useful when you have interacting threads. In your case, it appears to be that all the jobs are independent; I would use futures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With