Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When could Futures be more appropriate than Actors (or vice versa) in Scala?

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 Futures) and the latter (with Actors) approach and why the Future approach is considered better for the case described above.

like image 648
Michael Avatar asked Apr 19 '13 20:04

Michael


2 Answers

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.

like image 126
axel22 Avatar answered Oct 28 '22 17:10

axel22


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.

like image 21
user2533521 Avatar answered Oct 28 '22 19:10

user2533521