Book Image

Learning Concurrent Programming in Scala - Second Edition

By : Aleksandar Prokopec
Book Image

Learning Concurrent Programming in Scala - Second Edition

By: Aleksandar Prokopec

Overview of this book

Scala is a modern, multiparadigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Scala smoothly integrates the features of object-oriented and functional languages. In this second edition, you will find updated coverage of the Scala 2.12 platform. The Scala 2.12 series targets Java 8 and requires it for execution. The book starts by introducing you to the foundations of concurrent programming on the JVM, outlining the basics of the Java Memory Model, and then shows some of the classic building blocks of concurrency, such as the atomic variables, thread pools, and concurrent data structures, along with the caveats of traditional concurrency. The book then walks you through different high-level concurrency abstractions, each tailored toward a specific class of programming tasks, while touching on the latest advancements of async programming capabilities of Scala. It also covers some useful patterns and idioms to use with the techniques described. Finally, the book presents an overview of when to use which concurrency library and demonstrates how they all work together, and then presents new exciting approaches to building concurrent and distributed systems. Who this book is written for If you are a Scala programmer with no prior knowledge of concurrent programming, or seeking to broaden your existing knowledge about concurrency, this book is for you. Basic knowledge of the Scala programming language will be helpful.
Table of Contents (19 chapters)
Learning Concurrent Programming in Scala - Second Edition
Credits
Foreword
About the Author
Acknowledgements
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Concurrent collections


As you can conclude from the discussion on the 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 will 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) 
  Thread.sleep(500) 
} 

Instead of printing an array buffer...