Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning Concurrent Programming in Scala
Learning Concurrent Programming in Scala

Learning Concurrent Programming in Scala: Dive into the Scala framework with this programming guide, created to help you learn Scala and to build intricate, modern, scalable concurrent applications

eBook
$19.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning Concurrent Programming in Scala

Chapter 2. Concurrency on the JVM and the Java Memory Model

 

"All non-trivial abstractions, to some degree, are leaky."

 
 --Jeff Atwood

Since its inception, Scala has run primarily on top of the JVM, and this fact has driven the design of many of its concurrency libraries. The memory model in Scala, its multithreading capabilities, and its inter-thread synchronization are all inherited from the JVM. Most, if not all, higher-level Scala concurrency constructs are implemented in terms of the low-level primitives presented in this chapter. These primitives are the basic way to deal with concurrency—in a way, the APIs and synchronization primitives in this chapter constitute the assembly of concurrent programming on the JVM.

In most cases, you should avoid low-level concurrency in place of higher-level constructs introduced later, but we felt it important for you to understand what a thread is, that a guarded block is better than busy-waiting, or why a...

Processes and Threads

In modern, pre-emptive, multitasking operating systems, the programmer has little or no control over the choice of the processor on which the program will be executed. In fact, the same program might run on many different processors during its execution and sometimes even simultaneously on several processors. It is usually the task of the Operating System (OS) to assign executable parts of the program to specific processors—this mechanism is called multitasking, and it happens transparently for the computer user.

Historically, multitasking was introduced to operating systems to improve the user experience by allowing multiple users or programs to use resources of the same computer simultaneously. In cooperative multitasking, programs were able to decide when to stop using the processor and yield control to other programs. However, this required a lot of discipline on the programmer's part and programs could easily give the impression of being unresponsive...

Monitors and synchronization

In this section, we will study inter-thread communication using the synchronized statement in more detail. As we saw in the previous sections, the synchronized statement serves both to ensure the visibility of writes performed by different threads, and to limit concurrent access to a shared region of memory. Generally speaking, a synchronization mechanism that enforces access limits on a shared resource is called a lock. Locks are also used to ensure that no two threads execute the same code simultaneously; that is, they implement mutual exclusion.

As mentioned previously, each object on the JVM has a special built-in monitor lock, also called the intrinsic lock. When a thread calls the synchronized statement on an x object, it gains ownership of the monitor lock of the x object, given that no other thread owns the monitor. Otherwise, the thread is blocked until the monitor is released. Upon gaining ownership of the monitor, the thread can witness the memory...

Volatile variables

The JVM offers a more lightweight form of synchronization than the synchronized block, called volatile variables. Volatile variables can be atomically read and modified, and are mostly used as status flags; for example, to signal that a computation is completed or cancelled. They have two advantages. First, writes to and reads from volatile variables cannot be reordered in a single thread. Second, writing to a volatile variable is immediately visible to all the other threads.

Note

Reads and writes to variables marked as volatile are never reordered. If a write W to a volatile v variable is observed on another thread through a read R of the same variable, then all the writes that preceded the write W are guaranteed to be observed after the read R.

In the following example, we search for at least one ! character in several pages of the text. Separate threads start scanning separate pages p of the text written by a person that is particularly fond of a popular fictional hero...

The Java Memory Model

While we were never explicit about it throughout this chapter, we have actually defined most of the JMM. What is a memory model in the first place?

A language memory model is a specification that describes the circumstances under which a write to a variable becomes visible to other threads. You might think that a write to a variable v changes the corresponding memory location immediately after the processor executes it, and that other processors see the new value of v instantaneously. This memory consistency model is called sequential consistency.

As we already saw in the ThreadSharedStateAccessReordering example, sequential consistency has little to do with how processors and compilers really work. Writes rarely end up in the main memory immediately; instead, processors have hierarchies of caches that ensure a better performance, and guarantee that the data is only eventually written to the main memory. Compilers are allowed to use registers to postpone or avoid memory...

Summary

In this chapter, we showed how to create and start threads, and wait for their termination. We have shown how to achieve inter-thread communication by modifying the shared memory and by using the synchronized statement, and what it means for a thread to be in a blocked state. We have studied approaches to prevent deadlocks by imposing ordering on the locks and avoided busy-waits in place of guarded blocks. We have seen how to implement a graceful shutdown for thread termination and when to communicate using volatiles. We witnessed how the correctness of a program can be compromised by undesired interactions known as race conditions as well as data races due to the lack of synchronization. And, most importantly, we have learned that the only way to correctly reason about the semantics of a multithreaded program is in terms of happens-before relationships defined by the JMM.

The language primitives and APIs presented in this section are low-level; they are the basic building blocks...

Exercises

In the following set of exercises, you are required to implement higher-level concurrency abstractions in terms of basic JVM concurrency primitives. Some of these exercises introduce concurrent counterparts of sequential programming abstractions, and, in doing so, highlight important differences between sequential and concurrent programming. The exercises are not ordered in any particular order, but some of them rely on specific content from earlier exercises or this chapter.

  1. Implement a parallel method, which takes two computation blocks a and b, and starts each of them in a new thread. The method must return a tuple with the result values of both the computations. It should have the following signature:
    def parallel[A, B](a: =>A, b: =>B): (A, B)
  2. Implement a periodically method, which takes a time interval duration specified in milliseconds, and a computation block b. The method starts a thread that executes the computation block b every duration milliseconds. It should...
Left arrow icon Right arrow icon

Description

This book is a must-have tutorial for software developers aiming to write concurrent programs in Scala, or broaden their existing knowledge of concurrency. This book is intended for Scala programmers that have no prior knowledge about concurrent programming, as well as those seeking to broaden their existing knowledge about concurrency. Basic knowledge of the Scala programming language will be helpful. Readers with a solid knowledge in another programming language, such as Java, should find this book easily accessible.

What you will learn

  • Get to grips with the fundamentals of concurrent programming on modern multiprocessor systems, with a particular focus on the JVM concurrency model
  • Build highperformance concurrent systems from simple, lowlevel concurrency primitives
  • Express asynchrony in concurrent computations with futures and promises
  • Seamlessly accelerate sequential programs by using dataparallel collections
  • Implement reactive and eventbased programs declaratively with Rxstyle event streams
  • Design safe, scalable, and easytocomprehend inmemory transactional data models
  • Transparently create distributed applications that scale across multiple machines
  • Choose the correct concurrency abstraction and integrate different concurrency frameworks together in large applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 28, 2014
Length: 366 pages
Edition : 1st
Language : English
ISBN-13 : 9781783281411
Category :
Languages :
Concepts :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 28, 2014
Length: 366 pages
Edition : 1st
Language : English
ISBN-13 : 9781783281411
Category :
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 163.97
Scala for Java Developers
$48.99
Scala for Machine Learning
$65.99
Learning Concurrent Programming in Scala
$48.99
Total $ 163.97 Stars icon

Table of Contents

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

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(10 Ratings)
5 star 70%
4 star 30%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Thomas Ulrich Mar 21, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good, in-depth study of JVM concurrency intrinsics followed by Scala concurrency frameworks. In addition to the well-written study, each topic includes short, pragmatic, runnable example idioms demonstrating the current topic. The book concludes with a more comprehensive example comprising key concurrency libraries previously covered in book. Very well done! Highly recommended.
Amazon Verified review Amazon
MI Mar 05, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It starts from the basics and goes quite deep in several topics regarding JVM concurrency. One of the greatest strength of Scala is its concurrency abstractions and this book does a good job at explaining them.
Amazon Verified review Amazon
David De Jun 25, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Best book on concurrency, period.
Amazon Verified review Amazon
Robert Dawson Jan 16, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really enjoyed reading this book. The Scala community needed a manual such as this for a while now. Before this book, documentation on concurrent programming in Scala consisted mostly of online SIP documents, tutorials scattered across multiple websites, Stackoverflow answers and random blog posts. This results in scattered, incomplete and often convoluted information about Scala concurrency. Learning Concurrent Programming in Scala constitutes a readable and authoritative manual on using these concurrency libraries, with everything needed to get you started in one place. Although I recommend getting acquainted with sequential programming in Scala first, people who want to write concurrent programs in Scala should definitely read this book. That does not mean that the book is valuable only for Scala programmers - as someone with 11 years of industry experience in Java, I can honestly say that the concurrency novelties described in this book will be interesting to programmers coming from backgrounds different than Scala - there was much going on in the Scala world in the recent years, in which Java is still lagging behind (in fact, I was able to convince one of my colleagues at work to give Scala a try after he saw the introduction to the Rx framework in this book).The book starts by presenting the basics of JVM threading and memory model, which serves as the basic . Although this is more low-level than the rest of the concurrency frameworks in the book, the book does a good job arguing why you need to understand basic JVM concurrency, and when to use threads, locks and monitors. Chapter 3 shows the classic concurrency abstractions, such as concurrent data structures, atomics, and thread pools, and explains lock-free programming. Chapter 4 is where the fun begins - it explains the futures and promises concurrency package, shows how to use it for asynchronous programming, how to functionally compose asynchronous computations, how to write new future combinators using promises, shows how to do proper cancellation and blocking in futures, and explains the Scala Async framework. Chapter 5 introduces parallel collections, shows how they differ from normal collections, discusses operations that can be parallelized, shows how to implement custom parallel operations, and how to evaluate performance in your programs. Chapter 6 introduces Rx, asynchronous programming framework based on first-class event streams, and shows how Rx can be used to build user interfaces and streaming applications. Chapter 7 deals with software transactional memories, discusses how STMs work, shows how to avoid side-effects in transactions, how to execute transactions conditionally, explains how transactional collections work, and, importantly, illustrates how easy it is to create a custom transactional, thread-safe collection. Chapter 8 introduces actor programming using Akka, and covers asynchronous message sends, starting and looking up actors, the basics of actor supervision, as well distributing the application across multiple computers. While Akka is not completely covered in this book, as it is a big topic, this chapter teaches the essentials of Akka, and you will be able to write actor programs after you're done. Chapter 9 shows how to achieve scalability and top performance in concurrent applications, what are the common types of errors in concurrent applications, and how to debug them, and, finally, how to combine different concurrency technologies to build a real-world application - a remote file browser. This is the longest chapter, and arguably, it could have been split into two separate chapters.This is a hands-on book. Every concurrency concept is introduced through a minimal, self-contained example, and you are encouraged to code and try the examples yourself. In almost all places in the book, there is a snippet or a minimal example program that demonstrates or proves the preceding claim. Terms like starvation, deadlock, false sharing and rollbacks are never introduced without the corresponding example program that shows how these effects manifest themselves in practice. These programs are minimal examples, but are realistic and capture the essence of the corresponding real-world programs. I'm sure that, after having written and run the examples, the reader will have no problem recognizing the same effects in practice.Every chapter is concluded with a list of references, and practical program assignments, which test the knowledge from the corresponding chapter, and, in some cases, touch more advanced topics.What I especially liked about this book is that the author shows how different concurrency libraries can be used together. As an occasional by-stander in the Scala world, I've often witnessed propaganda and bias towards specific concurrency technologies. This is not the case only with Scala and its concurrency libraries, but also more broadly, with most programming technologies - proponents of specific programming technologies need to ruthlessly advertise their own frameworks to survive. As a result, they sometimes claim that their technology is the best, applicable to every problem or superior to alternatives. The author dismisses such attitude in two ways. First, he explains the underlying motivations for various concurrency primitives and shows their typical use-cases and usage scenarios. In doing so, he teaches the reader what a specific concurrency construct is most appropriate for. Second, he shows that concurrency primitives coming from different frameworks are not incompatible or mutually exclusive, but that they can and should be used together to tackle a task. For example, futures are ideal for issuing remote procedure calls or asynchronous requests, but parallel collections are more efficient for data-intensive tasks. Actors are great for distributed applications, but software transactional memory composes complex state and allows concurrent access to data. Still, the future can start a data-parallel computation or a transaction, and an Rx stream can send messages to an actor - these primitives support each other.What I'd wish to see more of are advanced concurrency concepts - how does one write his own concurrent data structure, or implement more advanced applications. The book touches performance engineering and achieving best program speeds, and, having read about it, I'd love to learn more. Perhaps a follow-up book about more advanced concurrent programming will address this. Still, this is overall a great book, and will teach you how to think about concurrent programming. I recommend it as an introductory book on concurrent programming, and modern concurrency paradigms.
Amazon Verified review Amazon
Manohar Jonnalagedda Apr 05, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book if a great resource for learning concurrent programming in Scala. Actually, it is great for learning concurrent programming in general!The book starts out with elementary concurrency building blocks. Each subsequent chapters builds on the blocks seen before, to introduce higher level abstractions, which make it easier to write more complex concurrent programs. At the same time, you won't be lost if you are only interested in later chapters: every chapter gives you sufficient context to understand it in isolation.I love that there are exercises that come with every chapter. They are by no means easy, but very fun and engaging. Many of them are not just programming tasks, but require you to sit down with pen and paper and think for a while. As a result the book satisfies two types of audiences: - The seasoned Scala developer who needs to refer to a resource every once in a while - A newbie who wants to learn about concurrent programming in general, and who is interested in building practical solutions with this knowledge. I definitely fall in this category of people, and am now completely hooked.All in all, this book strikes a pedagogical balance between being a text book and a reference book. Studying it cover to cover (and trying to solve some of the exercises) will give you great insights about concurrent programming.The only issue I have is with the quality (or lack thereof) of the illustrations/pictures. They have a poor scan look, they could definitely be much improved. Also, I wonder if there is going to be some sort of answer key, at least for a selected subset of the exercises.Get your copy now!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.