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! 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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learning Concurrent Programming in Scala
Learning Concurrent Programming in Scala

Learning Concurrent Programming in Scala: Practical Multithreading in Scala , Second Edition

Arrow left icon
Profile Icon Prokopec
Arrow right icon
zł59.99 zł158.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (16 Ratings)
eBook Feb 2017 434 pages 2nd Edition
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
Arrow left icon
Profile Icon Prokopec
Arrow right icon
zł59.99 zł158.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (16 Ratings)
eBook Feb 2017 434 pages 2nd Edition
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
eBook
zł59.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning Concurrent Programming in Scala

Chapter 1. Introduction

 

"For over a decade prophets have voiced the contention that the organization of a single computer has reached its limits and that truly significant advances can be made only by interconnection of a multiplicity of computers."

 
 --Gene Amdahl, 1967

Although the discipline of concurrent programming has a long history, it has gained a lot of traction in recent years with the arrival of multi core processors. The recent development in computer hardware not only revived some classical concurrency techniques but also started a major paradigm shift in concurrent programming. At a time when concurrency is becoming so important, an understanding of concurrent programming is an essential skill for every software developer.

This chapter explains the basics of concurrent computing and presents some Scala preliminaries required for this book. Specifically, it does the following:

  • Shows a brief overview of concurrent programming
  • Studies the advantages of using Scala when it comes to concurrency
  • Covers the Scala preliminaries required for reading this book

We will start by examining what concurrent programming is and why it is important.

Concurrent programming

In concurrent programming, we express a program as a set of concurrent computations that execute during overlapping time intervals and coordinate in some way. Implementing a concurrent program that functions correctly is usually much harder than implementing a sequential one. All the pitfalls present in sequential programming lurk in every concurrent program, but there are many other things that can go wrong, as we will learn in this book. A natural question arises: why bother? Can't we just keep writing sequential programs?

Concurrent programming has multiple advantages. First, increased concurrency can improve program performance. Instead of executing the entire program on a single processor, different subcomputations can be performed on separate processors, making the program run faster. With the spread of multicore processors, this is the primary reason why concurrent programming is nowadays getting so much attention.

A concurrent programming model can result in faster I/O operations. A purely sequential program must periodically poll I/O to check if there is any data input available from the keyboard, the network interface, or some other device. A concurrent program, on the other hand, can react to I/O requests immediately. For I/O-intensive operations, this results in improved throughput, and is one of the reasons why concurrent programming support existed in programming languages even before the appearance of multiprocessors. Thus, concurrency can ensure the improved responsiveness of a program that interacts with the environment.

Finally, concurrency can simplify the implementation and maintainability of computer programs. Some programs can be represented more concisely using concurrency. It can be more convenient to divide the program into smaller, independent computations than to incorporate everything into one large program. User interfaces, web servers, and game engines are typical examples of such systems.

In this book, we adopt the convention that concurrent programs communicate through the use of shared memory, and execute on a single computer. By contrast, a computer program that executes on multiple computers, each with its own memory, is called a distributed program, and the discipline of writing such programs is called distributed programming. Typically, a distributed program must assume that each of the computers can fail at any point, and provide some safety guarantees if this happens. We will mostly focus on concurrent programs, but we will also look at examples of distributed programs.

A brief overview of traditional concurrency

In a computer system, concurrency can manifest itself in the computer hardware, at the operating system level, or at the programming language level. We will focus mainly on programming-language-level concurrency.

The coordination of multiple executions in a concurrent system is called synchronization, and it is a key part in successfully implementing concurrency. Synchronization includes mechanisms used to order concurrent executions in time. Furthermore, synchronization specifies how concurrent executions communicate, that is, how they exchange information. In concurrent programs, different executions interact by modifying the shared memory subsystem of the computer. This type of synchronization is called shared memory communication. In distributed programs, executions interact by exchanging messages, so this type of synchronization is called message-passing communication.

At the lowest level, concurrent executions are represented by entities called processes and threads, covered in Chapter 2, Concurrency on the JVM and the Java Memory Model. Processes and threads traditionally use entities such as locks and monitors to order parts of their execution. Establishing an order between the threads ensures that the memory modifications done by one thread are visible to a thread that executes later.

Often, expressing concurrent programs using threads and locks is cumbersome. More complex concurrent facilities have been developed to address this, such as communication channels, concurrent collections, barriers, countdown latches, and thread pools. These facilities are designed to more easily express specific concurrent programming patterns, and some of them are covered in Chapter 3, Traditional Building Blocks of Concurrency.

Traditional concurrency is relatively low-level and prone to various kinds of errors, such as deadlocks, starvations, data races, and race conditions. You will usually not use low-level concurrency primitives when writing concurrent Scala programs. Still, a basic knowledge of low-level concurrent programming will prove invaluable in understanding high-level concurrency concepts later.

Modern concurrency paradigms

Modern concurrency paradigms are more advanced than traditional approaches to concurrency. Here, the crucial difference lies in the fact that a high-level concurrency framework expresses which goal to achieve, rather than how to achieve that goal.

In practice, the difference between low-level and high-level concurrency is less clear, and different concurrency frameworks form a continuum rather than two distinct groups. Still, recent developments in concurrent programming show a bias towards declarative and functional programming styles.

As we will see in Chapter 2, Concurrency on the JVM and the Java Memory Model, computing a value concurrently requires creating a thread with a custom run method, invoking the start method, waiting until the thread completes, and then inspecting specific memory locations to read the result. Here, what we really want to say is compute some value concurrently, and inform me when you are done. Furthermore, we would prefer to use a programming model that abstracts over the coordination details of the concurrent computation, to treat the result of the computation as if we already have it, rather than having to wait for it and then reading it from the memory. Asynchronous programming using futures is a paradigm designed to specifically support these kinds of statements, as we will learn in Chapter 4, Asynchronous Programming with Futures and Promises. Similarly, reactive programming using event streams aims to declaratively express concurrent computations that produce many values, as we will see in Chapter 6, Concurrent Programming with Reactive Extensions.

The declarative programming style is increasingly common in sequential programming too. Languages such as Python, Haskell, Ruby, and Scala express operations on their collections in terms of functional operators and allow statements such as filter all negative integers from this collection. This statement expresses a goal rather than the underlying implementation, allowing to it easy to parallelize such an operation behind the scene. Chapter 5, Data-Parallel Collections, describes the data-parallel collections framework available in Scala, which is designed to accelerate collection operations using multicores.

Another trend seen in high-level concurrency frameworks is specialization towards specific tasks. Software transactional memory technology is specifically designed to express memory transactions and does not deal with how to start concurrent executions at all. A memory transaction is a sequence of memory operations that appear as if they either execute all at once or do not execute at all. This is similar to the concept of database transactions. The advantage of using memory transactions is that this avoids a lot of errors typically associated with low-level concurrency. Chapter 7, Software Transactional Memory, explains software transactional memory in detail.

Finally, some high-level concurrency frameworks aim to transparently provide distributed programming support as well. This is especially true for data-parallel frameworks and message-passing concurrency frameworks, such as the actors described in Chapter 8, Actors.

Left arrow icon Right arrow icon

Key benefits

  • Make the most of Scala by understanding its philosophy and harnessing the power of multicores
  • Get acquainted with cutting-edge technologies in the field of concurrency, through practical, real-world applications
  • Get this step-by-step guide packed with pragmatic examples

Description

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.

Who is this book for?

If you are a Scala programmer with no prior knowledge about 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. Also if you have a solid knowledge in another programming language, such as Java, you should find this book easily accessible.

What you will learn

  • What you will learn from this book
  • ? Get to grips with the fundamentals of concurrent programming on modern multiprocessor systems
  • ? Build high-performance concurrent systems from simple, low-level concurrency primitives
  • ? Express asynchrony in concurrent computations with futures and promises
  • ? Seamlessly accelerate sequential programs by using data-parallel collections
  • ? Design safe, scalable, and easy-to-comprehend in-memory transactional data models
  • ? Transparently create distributed applications that scale across multiple machines
  • ? Integrate different concurrency frameworks together in large applications
  • ? Develop and implement scalable and easy-to-understand concurrent applications in Scala 2.12

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 22, 2017
Length: 434 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786462145
Category :
Languages :
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 22, 2017
Length: 434 pages
Edition : 2nd
Language : English
ISBN-13 : 9781786462145
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 zł20 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 zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 666.97
Akka Cookbook
zł221.99
Scala Design Patterns
zł246.99
Learning Concurrent Programming in Scala
zł197.99
Total 666.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
10. Reactors 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.8
(16 Ratings)
5 star 75%
4 star 25%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




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
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
Tihomir Gvero Mar 01, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an interesting and useful book that explores topics that help programmers understand and write correct and efficient concurrent programs in Scala. It is written for both the beginners and the programmers with more expertise in Scala programming, but who still want to develop and/or improve their concurrent programming skills. I really like this book, because it has many clear and easy to follow examples used to introduce many advanced aspects of concurrent programming. I enjoyed reading them. They cover several different topics introducing the most important concurrent programming abstractions. This includes the concurrency on the JVM (e.g., how to use Threads), traditional building blocks (thread pools, atomic variables and concurrent collections), asynchronous abstractions (e.g. Futures and Promises), the Scala parallel collections, the Scala reactive extension framework, transnational programming in Scala and Actors (e.g., the famous Akka framework). I bought a hard copy and so far I did not have any complaints about the quality. To sum up, it is the very informative and helpful book and the must-have in your Scala book collection. I sincerely recommend it!
Amazon Verified review Amazon
Anthony Lauder Jun 02, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought this when taking the Reactive Programming course on Coursera. This book turned out to be, in effect, the missing textbook for the course. It covers pretty much the same topics as the course, include RxScala, Futures, Akka Actors, and more. It does not replace online API documents, but does cover all the concepts deeply enough that you will be able to them using the API documents to fill in missing details.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.