O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required