Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Concurrent Programming in Scala

You're reading from   Learning Concurrent Programming in Scala Practical Multithreading in Scala

Arrow left icon
Product type Paperback
Published in Feb 2017
Publisher
ISBN-13 9781786466891
Length 434 pages
Edition 2nd Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Aleksandar Prokopec Aleksandar Prokopec
Author Profile Icon Aleksandar Prokopec
Aleksandar Prokopec
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Introduction FREE CHAPTER 2. Concurrency on the JVM and the Java Memory Model 3. Traditional Building Blocks of Concurrency 4. Asynchronous Programming with Futures and Promises 5. Data-Parallel Collections 6. Concurrent Programming with Reactive Extensions 7. Software Transactional Memory 8. Actors 9. Concurrency in Practice 10. Reactors

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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image