Book Image

Learning Concurrent Programming in Scala

By : Aleksandar Prokopec
5 (1)
Book Image

Learning Concurrent Programming in Scala

5 (1)
By: Aleksandar Prokopec

Overview of this book

Table of Contents (18 chapters)
Learning Concurrent Programming in Scala
About the Author
About the Reviewers

Concurrent collections

As you can conclude from the discussion on Java Memory Model in Chapter 2, Concurrency on the JVM and the Java Memory Model, modifying the Scala standard library collections from different threads can result in arbitrary data corruption. Standard collection implementations do not use any synchronization. Data structures underlying mutable collections can be quite complex; predicting how multiple threads affect the collection state in the absence of synchronization is neither recommended nor possible. We demonstrate this by letting two threads add numbers to the mutable.ArrayBuffer collection:

import scala.collection._
object CollectionsBad extends App {
  val buffer = mutable.ArrayBuffer[Int]()
  def asyncAdd(numbers: Seq[Int]) = execute {
    buffer ++= numbers
    log(s"buffer = $buffer")
  asyncAdd(0 until 10)
  asyncAdd(10 until 20)

Instead of printing an array buffer with 20 different elements, this example arbitrarily prints different...