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]) ...
Get Learning Concurrent Programming in Scala 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.