Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of using Futures over parallel collections in scala?

Is there a good reason for the added complexity of Futures (vs parallel collections) when processing a list of items in parallel?

List(...).par.foreach(x=>longRunningAction(x))  

vs

Future.traverse(List(...)) (x=>Future(longRunningAction(x)))
like image 548
mut1na Avatar asked Jan 08 '13 12:01

mut1na


People also ask

How do Futures work Scala?

Future represents a result of an asynchronous computation that may or may not be available yet. When we create a new Future, Scala spawns a new thread and executes its code. Once the execution is finished, the result of the computation (value or exception) will be assigned to the Future.

What is parallel collection in Scala?

The design of Scala's parallel collections library is inspired by and deeply integrated with Scala's (sequential) collections library (introduced in 2.8). It provides a parallel counterpart to a number of important data structures from Scala's (sequential) collection library, including: ParArray. ParVector. mutable.

Which method is used to execute the future in Scala?

The simplest way to create a future object is to invoke the Future. apply method which starts an asynchronous computation and returns a future holding the result of that computation. The result becomes available once the future completes.

What is Future sequence in Scala?

sequence takes a list of futures and transforms it into a single future of list in an asynchronous manner. For instance, assume that you have a list of independent jobs to be run simultaneously. In such a case, the list of futures can be composed into a single future of list using Future. sequence.


1 Answers

I think the main advantage would be that you can access the results of each future as soon as it is computed, while you would have to wait for the whole computation to be done with a parallel collection. A disadvantage might be that you end up creating lots of futures. If you later end up calling Future.sequence, there really is no advantage.

like image 167
Kim Stebel Avatar answered Sep 19 '22 19:09

Kim Stebel