gabox01
gabox01

Reputation: 315

Does concurrency in Scala happen automatically?

In Scala, when you write a function that has no side effect and is referentially transparent, does that mean, that the runtime environment automatically distributes it's processing to multiple threads?

Upvotes: 1

Views: 258

Answers (2)

fracca
fracca

Reputation: 2437

a function is not automatically run in parallel, but it can be made trivially to do so.

for instance, if you have a large collection, you can easily parallelise that operation by calling .par

(1 to 100000).par.map(_ * 2)

Futures, actors and other strategies are still valuable. Best tool for the job.

Upvotes: 3

om-nom-nom
om-nom-nom

Reputation: 62845

No, usually it does not mean so, unless you explicitly specify somehow that you want parallel processing (e.g. ScalaCL, parallel collections). It will be hard to impossible to it do automatically, for example:

def foo() = {
  val x = 1 + 2
  val y = 2 + 3
  x + y
}

Although, calculation of x and y can be parallelized, in practice it will be even slower (due to penalty incurred in parallelization) than serial code. So with automatic parallelization of everything you will end up with highly ineffective code for basic units.

You can say: why don't you parallelize code automatically and selectively (e.g. do not parallelize when it is not worth it), but such system have to rely on billions of factors, most important will be a specific architecture, current OS load, running profile, and many more (I guess in the end, we will have to solve halting problem). And this magic tracking system will involve it's own penalty.

Finally, although there is effect typing research, stock scala do not have any ways to make a distinction between side-effecting and non-side effecting functions.

After all, it is not that hard to parallelize scala code manually, as @fracca demonstrated.

Upvotes: 6

Related Questions