O'Reilly logo

Learning Concurrent Programming in Scala by Aleksandar Prokopec

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

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

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