Scala Parallel Collections
Creating and Using Parallel Collections
To create a parallel collection from a sequential collection, call the par method. To create a sequential collection from a parallel collection, call the seq method. This example shows how you turn a regular Vector into a ParVector, and then back again:
The par method can be chained, allowing you to convert a sequential collection to a parallel collection and immediately perform an action on it:
In these examples, the work is actually parceled out to multiple processing units, and then rejoined after the work is complete -without requiring developer intervention.
Do not use parallel collections when the collection elements must be received in a specific order.
Parallel collections perform operations concurrently. That means that all of the work is divided into parts and distributed to different processors. Each processor is unaware of the work being done by others. If the order of the collection matters then work processed in parallel is nondeterministic.(Running the same code twice can yield different results.)
If an operation is non-associative (if the order of execution matters), then the result on a parallelized collection will be nondeterministic.
Operations that have side effects, such as foreach, may not execute as desired on parallelized collections due to race conditions. Avoid this by using functions that have no side effects, such as reduce or map.