Difference between scala concurrent and non concurrent class under parallelsim

Viewed 85

In Scala - functional programming course on coursera, the following snippet is described to fail in the concurrent case. The snippet will succeed if the mutable.Set is replaced with a concurrent class.

def intersection(a: GenSet[Int], b: GenSet[Int]): Set[Int] = {
val result = mutable.Set[Int]()
for (x <- a) if (b contains x) result += x
result
}
intersection((0 until 1000).toSet, (0 until 1000 by 4).toSet)
intersection((0 until 1000).par.toSet, (0 until 1000 by 4).par.toSet)

Rule: Avoid mutations to the same memory locations without proper synchronization.

What is the difference between the concurrent and non-concurrent class, or what is the reason that the non-concurrent class can fail under parallelism?

2 Answers
Related