Book Image

Concurrent Patterns and Best Practices

By : Atul S. Khot
Book Image

Concurrent Patterns and Best Practices

By: Atul S. Khot

Overview of this book

Selecting the correct concurrency architecture has a significant impact on the design and performance of your applications. Concurrent design patterns help you understand the different characteristics of parallel architecture to make your code faster and more efficient. This book will help Java developers take a hands-on approach to building scalable and distributed apps by following step-by-step explanations of essential concepts and practical examples. You’ll begin with basic concurrency concepts and delve into the patterns used for explicit locking, lock-free programming, futures, and actors. You’ll explore coding with multithreading design patterns, including master, slave, leader, follower, and map-reduce, and then move on to solve problems using synchronizer patterns. You'll even discover the rationale for these patterns in distributed and parallel applications, and understand how future composition, immutability, and the monadic flow help you create more robust code. By the end of the book, you’ll be able to use concurrent design patterns to build high performance applications confidently.
Table of Contents (14 chapters)

A thread and its context


 As we saw in Chapter 1, Concurrency – An Introduction, a process is a container for threads. A process has executable code and global data; all threads share these things with other threads of the same process. As the following diagram shows, the binary executable code is read-only. It can be freely shared by threads as there is nothing mutable there.

The global data is mutable though and, as shown in the diagram, this is the source of concurrency bugs! Most of the techniques and patterns we will study in this book are ways to avoid such bugs.

Threads of the same process run concurrently. How is this achieved, given there is just one set of registers? Well, here's the answer: the thread context. This context helps a thread keep its runtime information independent of another thread. The thread context holds the register set and the stack.

The following diagram shows the various pieces:

 When the scheduler preempts a running thread, it backs up the thread context—that...