22

If I have this:

val a = Array(...)

and I write

a.par.map(e => someFunc(e))

Will the resulting collection be in the same order as the non-parallel collection?

Senthess
  • 17,020
  • 5
  • 23
  • 28
  • possible duplicate of [scala: with parallel collection, does aggregate respect order?](http://stackoverflow.com/questions/6303878/scala-with-parallel-collection-does-aggregate-respect-order) – Daniel C. Sobral Jul 11 '11 at 15:19
  • 3
    I now regret tagging it as duplicate. I have reread the other question, and the emphasis is not on iterate, but on aggregate. – Daniel C. Sobral Jul 11 '11 at 15:33

2 Answers2

25

Yes, but the function itself is executed without any particular order.

List(1,2,3).par foreach print // could print out 213
agilesteel
  • 16,775
  • 6
  • 44
  • 55
  • Is the order guaranteed for any collection that supports parallelism? – Senthess Jul 11 '11 at 14:19
  • Yes and btw I just noticed that there is a possible duplicate [link](http://stackoverflow.com/questions/6303878/scala-with-parallel-collection-does-aggregate-respect-order) – agilesteel Jul 11 '11 at 14:21
  • 1
    I saw the aggregate link, but I think it's not exactly duplicate. – Senthess Jul 11 '11 at 14:32
16

The parallel collections maintain all of the contracts of their non-parallel equivalents.

On collections in which a map operation preserves order, such as List, order will be preserved by the parallel map as well. On collections in which map does not preserve order, such as Set, order will not be preserved in the parallel version.

With unordered collections, there is no guarantee that the result of a parallel operation will even have the same traversal order as its non-parallel equivalent.

Aaron Novstrup
  • 20,967
  • 7
  • 70
  • 108
  • Would you have some reference (doc, or unit test in scala lib)? I trust you that it does in practice (I tried), but I need it to be guarantied – Juh_ Jun 06 '17 at 09:42
  • It's touched on here: http://docs.scala-lang.org/overviews/parallel-collections/overview.html (Note that transparency is given as a motivating quality for the design. The section on semantics discusses cases where non-determinism arises and states that results from partitioned computations are combined _in order_.) – Aaron Novstrup Jun 07 '17 at 15:24