Knowing When to Use Concurrency

We saw how the parallel collection runs some operations in parallel. Not all operations have parallel implementations, however. For example, the parallel collection provides the foldLeft, foldRight, and reduce methods so we can conveniently invoke them on these kinds of collections like we do on regular collections. Based on the context, we have to keep in mind that such operations will be sequential and not parallel.

 def​ addToConnected(connected ​:​ ​Int​, name ​:​ ​String​) ​=
  connected + (​if​ (isConnected(name)) 1 ​else​ 0)
 Time.code { () ​=>
  println(​"Number of folks connected: "​ +
  names.foldLeft(0) { addToConnected })
 }
 //Number of folks connected: 3
 //Time taken: 4.005546
 Time.code ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.