When can futures be more suitable than actors (or vice versa) in Scala?

Suppose I need to run several parallel tasks.

I can wrap each task in Future and wait for their completion. Alternatively, I can create an Actor for each task. Each Actor would complete its task (for example, after receiving a "start" message) and send the result back.

I wonder when I should use the first (with Future s) and the second (with Actor s) approaches and why the Future approach is considered better for the case described above.

+7
source share
3 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) 

In future results you can wait using Await.result , or you can display it even more / use it for understanding or set callbacks on it.

Compare this to creating an instance of all participants by sending them messages, encoding their receive blocks, receiving responses from them and disabling them, which usually requires more templates.

+6
source

As a rule, use the simplest concurrency model, which is suitable for your application, and not the most powerful. An order from the simplest to the most complex would be sequential programming β†’ parallel collections β†’ futures β†’ subjects of non-stability β†’ subjects from the point of view of state β†’ threads with programmatic transaction memory β†’ threads with explicit blocking β†’ threads with algorithms without blocking. Choose the first one on this list that solves your problem. The further you go to the list, the more difficulties and risks, so you better trade simplicity for conceptual power.

+5
source

I tend to think actors are useful when you have interacting streams. In your case, it seems that all tasks are independent; I will use futures.

0
source

All Articles